jQuery onLoad x jQuery onDomready

12

Every time I'm going to use JSFiddle I see options for initializing jQuery content via onLoad or onDomready .

I tested with most scripts I wrote and there was no functional difference whatsoever. Searching on Google has seen that one of the main differences is that via onLoad scripts only begin to run after all elements are loaded and this includes CSS, JS files, images, and so on, which can be useful if you need to load files in a certain order, but at some point one of these files makes reference to another one that has not yet been loaded, while viewing onDomready once loaded the HTML content of the page the scripts begin to be loaded already without necessarily the others have been.

  • Did I understand this difference?
  • Is there any further difference to be studied and perceived?
asked by anonymous 07.03.2014 / 13:21

2 answers

2

This you said is a bit confusing:

  

If you need to load JS files in a certain order, but at some point one of these files references another one that has not yet been uploaded, while viewing onDomready once loaded the HTML content of the page the scripts start to load already without necessarily having been others.

JavaScript files are by default loaded and executed in the order they are in the HTML source code, one after the other (never in parallel) - except for a few exceptions *.

If all of your scripts are loaded this way, it does not matter if the code inside them postpones the execution of something for DOMContentLoaded or window.onload . The result in both cases will be the same: postponed code will run after all other scripts have been loaded, and their codes executed (except for those postponed codes).

The exceptions I mentioned:

  • Scripts in <script> tags that use the async are loaded asynchronously, and executed as soon as they are loaded (in browsers that support this attribute).
  • Scripts in <script> tags that use the defer are loaded asynchronously, and executed only after the parsing of the complete document (in browsers that support this attribute). This is equivalent to running code just before the DOMContentLoaded event.
  • Scripts injected via document.createElement() + document.body.appendChild are loaded asynchronously, and run as soon as they are loaded.
07.03.2014 / 22:18
3

This is the biggest difference between the two events. With DOMContentLoaded , the scripts start running as soon as the DOM (the HTML of the page) is ready to be accessed by JavaScript. On the other hand, with window.onload the script expects all content to be loaded (including images, CSS, etc., as denoted in the question).

Perhaps the most relevant difference that was not pointed out is compatibility. window.onload is supported by old browsers, while the other event may not be as far as I know.

    
07.03.2014 / 13:42