Order of $(document).load() and $(document).ready() when deferring loading js

user984003 picture user984003 · Jan 6, 2013 · Viewed 42.9k times · Source

Before I change all my code, I just want to verify that I need to.

I have several inline js and jquery functions that are in the ready() function:

$(document).ready(function(){ do_something(); ...

Many of these functions rely on other functions that are contained in an external js document. They also use classes that are defined in the external style sheet.

Now I have just changed the loading of my external js and css such that it is deferred (as recommended by Google https://developers.google.com/speed/docs/best-practices/payload?hl=en#DeferLoadingJS):

 if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

This way the page is fully rendered, including all images, before it starts to load the JS.

This works fine. However, I'm wondering why and whether it always will. Isn't $(document).ready() executed before onLoad? Won't I risk not having the necessary functions defined when $(document).ready is executed?

So, do I need to change every $(document).ready to $(document).load()? Or, at least some of them? But then which onLoad() is executed first? The one that loads the external js (which is defined in the header) or the inline ones? what do I lose by changing ready to load? Might I, for example, risk that an event is not attached to an element when a user clicks on the element?

Btw, the jquery api is not deferred because that caused problems when I went to execute other code.

Answer

Chunky picture Chunky · Aug 27, 2013

Try using

 $(window).load(function(){
 dosomething();
 });

It will run the js after the whole page is loaded.

Avoid using

$(document).ready(function(){
 dosomething();
 }); 

It will run the js just after the loading of DOM.