The difference between jquery $(document).ready() and window.onload

The role of $(document).ready() in Jquery is similar to the window.onload method in traditional JavaScript, but it is different from the window.onload method.

 

1. Execution time

window.onload must wait until all elements in the page, including images, are loaded before executing.

$(document).ready() is executed after the DOM structure is drawn, without waiting for loading.

 

2. The number of writing is different

window.onload cannot be written more than one at the same time. If there are multiple window.onload methods, only one will be executed.

$(document).ready() can be written multiple times at the same time, and all can be executed

 

3. Simplified writing

window.onload is not simplified

$(document).ready(function(){}) can be shortened to $(function(){});

 

In my previous development, I generally used javascript, and I used jquery mode, that is, most of the time, the first line was written:

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

        At this time, it is not necessary to wait for all js and images to be loaded before executing some methods.

However, sometimes, you must wait for all elements to be loaded before you can execute some methods, for example, some pictures or other aspects have not been loaded. At this time, clicking some buttons will lead to unexpected situations. , at this time, you need to use: 

$(window).load(function() {
         $("#btn-upload").click(function(){ //For example:
                uploadPhotos();
          });
});

        Several reasons to use $(window).load(function(){...}) instead of body.onload() are as follows :

First of all, they are executed after all elements of the page (including html tags and all referenced images, Flash and other media) are loaded, which is what they have in common.

 

Don't use body.onload() Reason 1 :

If we want to load multiple functions at the same time, we have to write

<body onload="fn1(),fn2()"></body> looks neither beautiful nor convenient for later project maintenance. If we use $(window).load(), we can load multiple functions in this way, the code as follows:

$(window).load(function() {
            alert("hello, I'm jQuery!");
  });
 $(window).load(function() {
        alert("hello, I am also jQuery");
 });

        Writing it this way will execute both functions from top to bottom and look much prettier.

 

Do not use body.onload() Reason 2:

Using body.onload() cannot completely separate js and html, which is a very serious problem (it will affect the later maintenance of the project).

In addition, using $(window).load(function(){...}) and body.onload() have the same problem: they both need to wait until all the content of the page is loaded before executing. 

However, when the network speed is relatively slow, it often takes a long time to load a page (several seconds to more than ten seconds, or even longer...), so we often encounter that the page has not been fully loaded yet. The user is already operating the page, so the effect of the page is different from what we expected, so in this case it is recommended to use $(document).ready(function(){}), or shorthand It is $(function(){}), because it will be executed after the dom element of the page is loaded, without waiting for the image or other media to be downloaded.

But sometimes we do need to wait until everything on the page is loaded before executing the function we want to execute, so should we use $(window).load(function(){...}) or $(function (){}) often need to make different choices in combination with specific needs .

Finally attach a piece of jQuery code that executes before all DOM elements are loaded:

<script type="text/javascript">
       (function() {
               alert("DOM hasn't loaded yet!");
        })(jQuery)
  </script>

 window.onload cannot be written more than one at the same time, if there are more than one, only the last one will be executed:

window.onload = function(){
          alert(“text1”);
};
window.onload = function(){
         alert(“text2”);
};

 The above code will only execute the second one, with only one popup: text2.

 However, if there are multiple $(document).ready, they will be executed in sequence:

$(document).ready(function(){
          alert(“Hello World”);
});
$(document).ready(function(){
          alert(“Hello again”);
});

 The above code will pop up in sequence: Hello World, Hello again.

 

illustrate:

Since the events registered in the $(document).ready() method will be executed as soon as the DOM is ready, it is possible that the element's associated file has not been downloaded at this time. For example, the html related to the image has been downloaded and parsed into the DOM tree, but it is very likely that the image has not been loaded, so attributes such as the height and width of the image are not necessarily valid at this time.

To solve this problem, you can use another method in Jquery about page loading---load() method:

The Load() method binds a handler to the element's onload event .

If the handler is bound to the window object , it will fire after everything ( including windows, frames, objects, images, etc. ) has loaded;

If the handler is bound to an element , it will fire after the element's content has loaded.

 

Recently, when I changed a page embedded in a frame, I used jquery for the effect, and the page itself was also bound to the onload event. After the modification, the test under Firefox is normal and smooth, and under IE, it takes more than ten seconds for the effect of jquery to appear, and the daylily is cold.

  At first I thought it was a conflict with the method of onload loading itself. The common saying on the Internet is that $(document).ready() is executed after the DOM parsing of the page is completed, and the onload event is executed after all resources are prepared, that is to say, $(document).ready() is to be executed in Executed before onload, especially when the page images are larger and larger, the time difference may be larger. However, on my page, the pictures have been displayed for more than ten seconds, and the effect of jquery has not been seen.

  I deleted the onload loading method, and the result is still the same. It seems that there is no need to change the original onload event binding to $(document).ready(). So what makes Firefox work and IE works? Then I debugged and found that the original bound onload method under IE was executed before the content of $(document).ready(), while Firefox executed the content of $(document).ready() first, and then executed the original onload method . This doesn't seem to be completely consistent with the online statement, huh, it's a bit interesting,,,,,

  Look through the source code of jquery to see how $(document).ready() is implemented: 

if ( jQuery.browser.msie && window == top ) (function(){
        if (jQuery.isReady) return;
        try {
                document.documentElement.doScroll("left");
        } catch( error ) {
      setTimeout( arguments.callee, 0 );
       return;
   }
   // and execute any waiting functions
   jQuery.ready();
})();

jQuery.event.add( window, "load", jQuery.ready );

 The result is very clear, IE only executes the content of $(document).ready() first, and then executes the original onload method, just like Firefox when the page is not embedded in the frame.

For the page embedded in the frame, it is only bound to be executed on the load event, so it is naturally the turn after the original onload binding method is executed. In this page, there is an inaccessible resource in the test environment, and the delay of more than ten seconds is the time difference it magnifies.

The above is the whole content of this article. To learn more about the syntax of jQuery, you can check: " jQuery 1.10.3 Online Manual ".

 

 

Reference article address: http://www.jb51.net/article/21628.htm

 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326898897&siteId=291194637