You can use windows. onload event, but in onload's view, it is only after all the things (img, iframe, and other resources) on the page are loaded. If there are large images in the page, it will be executed long after the page is displayed.
If you only need to perform operations on the DOM, there is no need to wait until all the pages are loaded. We need a faster method. Firefox has a DOMContentLoaded event that can be easily solved. Unfortunately, IE does not.
MSDN's method of JSCRIPT is unremarkable. When the page DOM is not loaded, an exception occurs when the doScroll method is called. If no exception occurs, the page DOM is loaded. Therefore, for Mozilla & Opera browsers, there is a ready-made DOMContentLoaded event after the dom tree is loaded. For Safari, there is a document. onreadystatechange event. When this event is triggered, if document. readyState = complete, it can be considered that the dom tree has been loaded.
For ie, there is also a document. onreadystatechange event in iframe. for ie in non-iframe, it is only possible to continuously judge whether the dom has been loaded by executing doScroll.
In this example, execute document.doc umentElement. doScroll ('left') every Five milliseconds '). In ie8, a document. onreadystatechange event occurs in the non-iframe window. You can also use this function when building your own framework.
Copy codeThe Code is as follows:
(Function (){
Var isReady = false; // checks whether the onDOMReady method has been executed.
Var readyList = []; // Save the method to be executed in this array
Var timer; // timer handle
Ready = function (fn)
{
If (isReady)
Fn. call (document );
Else
ReadyList. push (function () {return fn. call (this );});
Return this;
}
Var onDOMReady = function (){
For (var I = 0; I <readyList. length; I ++)
{
ReadyList [I]. apply (document );
}
ReadyList = null;
}
Var bindReady = function (evt)
{
If (isReady) return;
IsReady = true;
OnDOMReady. call (window );
If (document. removeEventListener)
{
Document. removeEventListener ("DOMContentLoaded", bindReady, false );
}
Else if (document. attachEvent)
{
Document. detachEvent ("onreadystatechange", bindReady );
If (window = window. top ){
ClearInterval (timer );
Timer = null;
}
}
};
If (document. addEventListener ){
Document. addEventListener ("DOMContentLoaded", bindReady, false );
}
Else if (document. attachEvent)
{
Document. attachEvent ("onreadystatechange", function (){
If (/loaded | complete/). test (document. readyState ))
BindReady ();
});
If (window = window. top)
{
Timer = setInterval (function (){
Try
{
IsReady | document.doc umentElement. doScroll ('left'); // you can run doScroll in IE to determine whether the dom has been loaded.
}
Catch (e)
{
Return;
}
BindReady ();
}, 5 );
}
}
})();
The usage is as follows:
Copy codeThe Code is as follows:
Ready (dosomething); // dosomething is an existing function.
// You can also use the closure.
Ready (function (){
// Here is the logic code
});