When we want to execute a function after page loading, we will surely think of onload. But in the browser's view, onload can only happen after all the things on the page are loaded, but it's too late. 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!
The Code is as follows:
Function IEContentLoaded (w, fn ){
Var d = Doc ument, done = false,
// Only fire once
Init = function (){
If (! Done ){
Done = true;
Fn ();
}
};
// Polling for no errors
(Function (){
Try {
// Throws errors until after ondocumentready
D.doc umentElement. doScroll ('left ');
} Catch (e ){
SetTimeout (arguments. callee, 50 );
Return;
}
// No errors, fire
Init ();
})();
// Trying to always fire before onload
D. onreadystatechange = function (){
If (d. readyState = 'complete '){
D. onreadystatechange = null;
Init ();
}
};
}
This function was released by Diego Perini in,
It is also widely recognized that many open-source frameworks use this method, such as ready in JQuery.
If you need to use IE's DomReady later, it will be him.
Usage:
IEContentLoaded (document. getElementById ("test"), test );
Function test (){}