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

Source: Internet
Author: User

$ (document). Ready and window.onload are all functions that are executed after the page is loaded, and in most cases the difference is small, but there are differences.

$ (document). Ready: The DOM structure is executed after it has been drawn, without having to wait until the load is complete. This means that the DOM tree is loaded and executed without having to wait until the page is loaded with pictures or other external files. And you can write multiple .ready.

Window.onload: All elements of the page are loaded, including images. Can only be performed once.


So, $ (document). Ready is executed earlier than window.onload. And can write multiple, see code:

1 //The following code does not execute correctly:2Window.onload =function()3 { 4 alert ("Text1");5 }; 6Window.onload =function()7 { 8 alert ("Text2");9 }; Ten //The result outputs only the second one can write multiple One //The following code executes correctly: A$ (document). Ready (function() - {  - alert ("Hello World"); the });  -$ (document). Ready (function() - {  - alert ("Hello again"); + });  -Results are output twice

If you need to get the property value of a DOM binding element, it is best to use window.onload because he is executed when all elements are loaded, if you use $ (document). Ready,dom has been loaded, but the DOM bound element attribute is not loaded, so the attribute does not take effect. To solve this problem, you can use another method in Jquery about page loading---the load () method. The Load () method binds a handler function in the OnLoad event of the element. If the handler is bound to a Window object, it fires after all content (including Windows, frames, objects, images, and so on) is loaded, and if the handler is bound to the element, it is triggered after the element's contents have been loaded.

$ (window). Load (function  () {});  //  function  () {}

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.