The difference between read in jQuery and the onload function in JavaScript

  • 2020-03-30 03:46:18
  • OfStack

In JavaScript, the onload function is the most frequently used, almost involved in JavaScript children's shoes are indispensable to touch it. This function is used to wait for the page to be fully loaded before executing the statements in the code block, because it is usually used when JavaScript is loaded in the header in the order of execution of the document stream.


window.onload = function(){
    //Execute the code block here
when the page is loaded };

There is also a corresponding function in jQuery that waits for the page to load and then executes the code block

$(document).ready(function(){
    //Execute the code block here when the page is loaded.       < br / > });

These two seemingly identical features are actually quite different.

Onload is executed not only after the DOM tree is created, but also after all external resources have been loaded and the entire page is displayed in the browser window. These resources include not only image resources, but also flash videos embedded on the page. If there are too many images or flash, it will take a long time to load, which means more time to delay the execution of the code block.

The ready() method in jQuery simply waits for the document structure to be fully parsed and the browser to turn the HTML into a DOM tree before executing the code block. Notice here that the DOM alone has nothing to do with the images in the page, flash, and other external resources.

This shows that the ready() method in jQuery will shorten the wait time.

There is another way, of course, to put all the scripts in. Body> After the tag, the page will execute in document flow order, which will also result in the onload effect in JavaScript or the ready() effect in jQuery, which will render the content of the page faster.


Related articles: