18

I have one question; In my ASP.NET MVC web application have to do certain validation once page and all controls got loaded.

In Javascript I was using below line of code for calling a method:

window.load = JavascriptFunctionName ; 

Someone from my team asked me not used above line of code, instead use JQuery to do the same:

 document.attachEvent("onreadystatechange", function() {
        if (document.readyState === "complete") {
            CheckThis();

        }
    });

Please help me in understanding what is the difference between two. When I tested by keeping alert in both jQuery check is executing first and calling the CheckThis function where as window.load is taking some time and executing after it. Please suggest

1
  • Here's a pen that shows the order in which all events fire, the jQuery approach isn't necessarily the right choice under all circumstances: codepen.io/pen/jagxdb.
    – Shikkediel
    Dec 10, 2017 at 2:47

3 Answers 3

9

window.load - This runs when all content is loaded, including images.

document.ready - This runs when the DOM is ready, all the elements are on the page and ready to do, but the images aren't necessarily loaded.

Here's the jQuery way to do document.ready:

$(function() {
  CheckThis();
});

If you wanted to still have it happen on window.load, do this:

$(window).load(function() {
  CheckThis();
});
2
  • 5
    readyState has 3 options loading, interactive and complete, which one are you talking about in here? complete according to the docs means that all sub-resources (including images I suppose...) are loaded. Then it says it indicates the load event has been fired.
    – Alvaro
    Jan 12, 2016 at 10:33
  • Might need an update. Using load like that was already deprecated but has now been removed.
    – Shikkediel
    Dec 9, 2017 at 20:41
5

window.load triggered when your page completely loaded (with images, banners, etc.), but document.readyState triggered when DOM is ready

3

The ready handler executes as soon as the DOM has been created, without waiting for all external resources to be loaded.

Since you've using jQuery, a more concise, browser agnostic, and widely used syntax for it is:

$(function(){  
   CheckThis();
}); 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.