1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <title>domReady</title> 8 9 </head> 10 <body> 11 <h1 id="header">这里是h1元素包含的内容</h1> 12 <h1 id="header2">这里是h1元素包含的内容</h1> 13 <img src="http://hiphotos.baidu.com/90008com/pic/item/fdaef1ea2eea7ff3d539c904.jpeg" alt=""> 14 </body> 15 <script> 16 var d=window.document; 17 var time1=null,time2=null,time=null; 18 time=new Date().getTime(); 19 domReady(function(){ 20 time1 = new Date().getTime(); 21 d.getElementById("header").style.color="red"; 22 d.getElementById("header").innerHTML="DOM Ready 加载完毕!耗时:" + (time1-time) +"毫秒。"; 23 }) 24 window.onload=function(){ 25 time2= new Date().getTime(); 26 d.getElementById("header2").innerHTML="window onload 加载完毕! 耗时:" + (time2-time) + "毫秒。 <br />DOMReady 比 window.onload 快" + (time2-time1) +"毫秒"; 27 } 28 </script> 29 </html>
1 function domReady(fn){ 2 if(document.addEventListener){ //如果是FF,Chrome,Opear最新浏览器 3 document.addEventListener("DOMContentLoaded", fn ,false); 4 } else { //如果是IE浏览器 5 IEContentLoaded(fn); 6 } 7 function IEContentLoaded(fn){ 8 var d = window.document; 9 var done = false; 10 var init = function(){ 11 if( !done ){ 12 done = true; 13 fn(); 14 } 15 }; 16 (function(){ 17 //DOM树未加载完成会抛出错误 18 try{ 19 console.log(2); 20 d.documentElement.doScroll('left'); 21 } 22 //再试一次 23 catch(e){ 24 console.log(1); 25 setTimeout(arguments.callee,50); 26 return; 27 } 28 //没有错误表示dom树加载完毕,继续执行下面的代码 29 init(); 30 })(); 31 //监听document的加载状态 32 d.onreadystatechange = function(){ 33 //如果用户在domready之后绑定的函数,那就立即执行 34 if(d.readyState == 'complete'){ 35 d.onreadystatechange = null; 36 init(); 37 } 38 }; 39 } 40 }