Distinction and execution sequence of $of window. load and $of document. ready in JQ

  • 2021-07-26 06:02:45
  • OfStack

JQ $(document). ready () should be used very much, basically every JS script has this function appear sometimes even more, then another 1 loading function $(window). load appears relatively few times, the following for everyone to introduce the difference between the two and their execution order

In general, the basic order of loading a page response is: domain name resolution- > Load html- > Load js and css- > Load pictures and other information.
So when do we use $(document). ready () and $(window). load when we write JS scripts, let's first look at the functionality of both

1. $(document).ready()

Literally, the document is ready. That is, the browser has loaded and parsed the entire html document, the dom tree has been established, and then this function is executed

The writing in native JavaScript is as follows:


It is written in jQuery as follows:




2. $(window).load

Execute after all elements in the Web page (including pictures in the page, css files, etc.) are fully loaded into the browser

In the native JavaScript, it is written as follows:

window.onload = function(){ 

It is written in jQuery as follows:


The difference between the two is:

1. Different execution times

$(document). ready () is executed after the page has finished loading the HTML and established the DOM tree, but this does not mean that the

Some data have all been loaded, and some large pictures will be loaded for a long time after the establishment of DOM tree, and

$(window). load () is the entire page has been loaded before execution, including pictures and other related files.

2. The number of times it can be executed is different

$(document). ready () can appear several times in JavaScript code, and the functions or code inside can be executed; While $(window). load () can only appear once in JavaScript code. If there are multiple $(window). load (), only the function or code in the last $(window). load () will be executed, and the previous $(window). load () will be covered.

3. Different efficiency of implementation

If you want to add onclick attribute nodes to the element nodes of dom, it is more efficient to use $(document). ready () than to use $(window). load (). But at some point you have to use $(window). load ()

Summary 1 is: $(window). load () in $(document). ready after the execution, and all the contents of the page will be loaded after the completion of the execution, the use of both the timing of a clear, you can decide.

Related articles: