From: http://blog.guoshuang.com/david/showlog.asp? Log_id = 2964
The original English text is here:
Http://dean.edwards.name/weblog/2005/09/busted/
The main idea is as follows:
We often use window. onload to process pages. When page loading is complete, we will do something. But this window. onload isPage loadedAnd even images. What we usually need isDocument Dom loaded!
This is the original method.
<SCRIPT type = "text/JavaScript"> <br/> function Init () {<br/> alert ("the page has been loaded! "); <Br/>}< br/> window. onload = Init; <br/> </SCRIPT> <br/>[Ctrl + A select all tips: you can modify some code and then press run]
For Mozilla
<SCRIPT type = "text/JavaScript"> <br/> // for Mozilla browsers <br/> If (document. addeventlistener) {<br/> document. addeventlistener ("domcontentloaded", function () {alert ("dom loaded! ")}, Null); <br/>}< br/> </SCRIPT> <br/>[Ctrl + A select all tips: you can modify some code and then press run]
For ie browsers, you can use the defer attribute unique to IE.
<SCRIPT defer type = "text/JavaScript"> <br/> alert ("dom loaded! ") <Br/> </SCRIPT> <br/>[Ctrl + A select all tips: you can modify some code and then press run]
Non-ie browsers will ignore defer and directly execute scriptsCodeYou can block non-ie browsers in two ways.
Conditional comments condition Annotation
<! -- [If IE]> <br/> <SCRIPT defer type = "text/JavaScript"> <br/> alert ("dom loaded! ") <Br/> </SCRIPT> <br/> <! [Endif] --> <br/>[Ctrl + A select all tips: you can modify some code and then press run]
Conditional compilation condition editing
<SCRIPT defer> <br/> // for Internet Explorer <br/>/* @ cc_on @ */<br/>/* @ if (@ _ Win32) <br/> alert ("dom loaded! ") <Br/>/* @ end @ */<br/> </SCRIPT> <br/>[Ctrl + A select all tips: you can modify some code and then press run]
In addition, the browser should use the first one at the top. The last problem is to avoid the problem of running onload multiple times and add judgment.
<SCRIPT type = "text/JavaScript"> <br/> function Init () {<br/> // quit if this function has already been called <br/> If (arguments. callee. done) return; </P> <p> // flag this function so we don't do the same thing twice <br/> arguments. callee. done = true; </P> <p> // create the "Page loaded" message <br/> var text = document. createtextnode ("Page loaded! "); <Br/> var message = document. getelementbyid ("message"); <br/> message. appendchild (text); <br/>}; </P> <p>/* for Mozilla */<br/> If (document. addeventlistener) {<br/> document. addeventlistener ("domcontentloaded", init, null ); <br/>}</P> <p>/* for Internet Explorer */<br/>/* @ cc_on @ */<br/>/* @ if (@ _ Win32) <br/> document. write ("<SCRIPT defer src = ie_onload.js> <" + "/SCRIPT> "); <br/>/* @ end @ */</P> <p>/* for other browsers */<br/> window. onload = Init; <br/> </SCRIPT> <br/> <p id = "message"> </P> <br/>
I really admire this kind of research spirit from foreigners. It is worth learning so much from such a small question. :(