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

Before I change all my code, I just want to check what I need.

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

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

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

Now I just changed the loading of my external js and css so that it is delayed (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; 

Thus, the page is fully displayed, including all images, before it starts loading JS.

It works great. However, I wonder why and whether it will always be. Isn't $ (document) .ready () executed before onLoad? Would I risk not having the necessary functions defined when executing $ (document) .ready?

So, do I need to change every $ (document) .ready to $ (document) .load ()? Or at least some of them? But then which of onLoad () is executed first? One that loads external js (which are defined in the header) or inline? What am I losing by changing the readiness for downloading? Can I, for example, risk that the event is not tied to the element when the user clicks on the element?

Btw, jquery api is not delayed because it caused problems when I went to execute other code.

+4
source share
2 answers

Try using

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

It will start js after loading the whole page.

Avoid using

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

It will start js immediately after loading the DOM.

+3
source

The order of execution is as follows:

  • ready() started when the DOM (HTML) is ready and scripts are loaded.
  • load() fires when everyone else has finished loading: HTML, Scripts, CSS, Images

As a rule, place all scripts outside of ready-made and bootable handlers, therefore functions are loaded by the time they are called. Then save the event listeners inside the finished handler and call any functions on demand.

The high-level JS structure is as follows:

  • JQuery library
  • Plugins / third-party scripts
  • User scripts
  • $(document).ready() packaging minimal JS logic to listen for DOM events
+1
source

All Articles