Home >Web Front-end >JS Tutorial >The difference between read in jQuery and onload function in JavaScript_jquery

The difference between read in jQuery and onload function in JavaScript_jquery

WBOY
WBOYOriginal
2016-05-16 16:38:401047browse

In JavaScript, the onload function is the most frequently used, and almost everyone involved in JavaScript must come into contact with it. The function of this function is to wait for the web page to be completely loaded before executing the statements in the code block, because it is usually used when loading JavaScript in the header according to the execution order of the document flow.

Copy code The code is as follows:

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

There is also a corresponding function in jQuery, which is to wait for the web page to be loaded before executing the code block
Copy code The code is as follows:

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

The above two functions seem to be the same, but they are actually very different.

onload will be executed not only after the DOM tree is created, but also after all external resources are 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 is spent delaying the execution of the code block.

The ready() method in jQuery only needs to wait for the document structure to be fully parsed and the browser has converted the HTML into a DOM tree before executing the code block. Note here that it is only the DOM, pictures in the web page, flash, etc. External sources are irrelevant.

It can be seen that the ready() method in jQuery will shorten the waiting time.

Of course there is another way, which is to put all the scripts after the tag. In this case, the web page will be executed in the order of the document flow, and the effect of onload in JavaScript or ready() in jQuery will also be achieved, and this method Web content will be displayed faster.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn