Javascript checks whether the dom has been loaded.

Source: Internet
Author: User

First, we need to clarify two concepts

1. window. onload: After the page is loaded, all components (images, etc.) on the page are available.

2. dom loading: The file object model is loaded before the window. onload event.

It can be seen that when a page contains a large number of components (especially images), the loading time of the above two types will be very long, and it is particularly important to judge when the dom is loaded.

Some page components (css, image, flash) will not cause the page DOM to fail to be built. Only JS will block the construction of DOM nodes on the page

Function init (){

// If the function is called multiple times, the system returns

If (arguments. callee. done) return;

//

Arguments. callee. done = true;

// Clear the timer set for safari

If (_ timer) clearInterval (_ timer );

Alert (document. getElementById ("test"). id );

};

// Firefox and opera9.0

If (document. addEventListener ){

Document. addEventListener ("DOMContentLoaded", init, false );

}

// Ie

Document. write ("<script id = __ie_onload defer src = javascript: void (0)> <\/script> ");

Var script = document. getElementById ("_ ie_onload ");

Script. onreadystatechange = function (){

If (this. readyState = "complete "){

Init (); // call the onload handler

}

};

// Safari

If (/WebKit/I. test (navigator. userAgent) {// sniff

Var _ timer = setInterval (function (){

If (/loaded | complete/. test (document. readyState )){

Init (); // call the onload handler

}

}, 10 );

}

// Other browsers directly use the window. onload event

Window. onload = init;

Source: http://www.wellpeter.com /? P = 162

Related Article

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.