DOMContentLoaded and window. onload, domcontentloaded
I believe that anyone who writes js knows window. onload, but not everyone knows DOMContentLoaded. In fact, even if you don't know it, you may often use it.
Generally, the DOMContentLoaded event must be in the window. execute before onload. When the DOM tree is built, the DOMContentLoaded event is executed, while the window. onload is executed only when the page is loaded, including images and other elements. Most of the time we just want to bind events to elements after the DOM tree is built, we don't need image elements, and sometimes loading external domain images is very slow.
We can write code to test the two events:
Javascript code (jQuery1.4.1 introduced ):
if (document.addEventListener){ function DOMContentLoaded(){ $( "#status" ).text( "DOM is ready now!" ); } document.addEventListener( "DOMContentLoaded" , DOMContentLoaded, false ); } window.onload= function (){ $( "#status" ).text( "DOM is ready AND wondow.onload is excute!" ); } |
Body of HTML code:
To see the effect clearly, write a simple PHP file to provide delayed image loading. The Code is as follows:
sleep(5);header('Location:./delay.png');
In firefox, chrome, and opera, we can clearly see that before the image is loaded, the Section with id as status has displayed "DOM is ready now !", After five seconds, after the image is loaded, this section displays "DOM is ready AND wondow. onload is excute !"
This Code does not work in IE. On the one hand, it is because I used addEventListener and made a judgment before the start. If this rule does not exist, this event is not added. The reason for this is that IE does not support the DOMContentLoaded event. For the simplicity of the Code, it is not written for IE. Although IE does not have this event, we can simulate this event. A common method is to determine if the doScroll of the element is successful, the DOM loading is completed.
Common libraries provide the event compatibility with the encapsulation of various browsers. If you are a jQuery user, you may frequently use $ (document ). ready (); or $ (function () {}) all use the DOMContentLoaded event.
Who should execute windowonload and pageload first?
Window. onload is executed before. Your request will be sent to the server, the server executes page_load, and then response returns, and then the window. onload of the client (that is, your browser) will be executed.
In js, why does windowonload and windowonunload run together?
When the page leaves, onunload is called. When the page is refreshed, The onunload of the previous page is called, and then the onload is called.