This ondomready is more attractive.
First, let's explain why we need to extract jquery's ready method?
In most cases, when you are working on the front-end, you need to execute some functions immediately when loading the DOM tree, such as initializing the navigation bar.
But I am not willing to introduce the entire jquery library for this purpose, so I extracted jquery's ready method and used it separately.
You can also use this function when building your own JS framework.
Repeat it. What is our slogan?
No line of code is redundant for tough applications !!!
Ready-from-jquery
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> ready method extracted from jquery </title>
<SCRIPT type = "text/JavaScript">
(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 );
}
}
})();
// Usage
Ready (navinit); // navinit is an existing function.
// Or
Ready (function (){
Navinit ();
});
Function navinit (){
Document. getelementbyid ("info"). innerhtml = "document. getelementbyid (" info "). innerhtml = OK ";
}
</SCRIPT>
</Head>
<Body>
<Div id = "info"> </div>
</Body>
</Html>