document的ready事件通常會比window的onload事件先發生,為什么呢?
因為document的ready是在瀏覽器加載解析並構建完doc文檔模型時發生的,而window的onload是整個文檔的內容加載完成時才會發生。
舉個很簡單的例子:
1個頁面有幾十張比較大的圖片(img),當網速慢的時候最能看出效果,訪問這個頁面瀏覽器就會先去構建doc模型,然后再去請求圖片,在構建doc模型完成就會執行document的ready事件,而window的onload事件得要等所有圖片加載完成才會執行。
<!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>測試</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style type="text/css"> body{padding:0px;margin:0px;} #main {margin:auto;padding:0;background: yellow;width:90%;} #layout { height: 300px; width: 80%; background: #99FFcc; margin:auto; height:50px;} </style> <script> window.onload = function(){ console.log("window is onload"); } document.onreadystatechange = function(){ if(document.readyState == "complete"){ //當頁面加載狀態為完全結束時進入 console.log('document is onload'); } if(document.readyState == "interactive"){ //DOM構建了就會執行,先與complete執行 console.log('document is interactive ,so DOM obj is '+ document.getElementById('img1')); } }; </script> </head> <body onload="console.log('body is onload')"> 測試事件 <img src="http://pic5.bbzhi.com/qichebizhi/mingchegaoqingbizhijihe/mingchegaoqingbizhijihe_427614_11.jpg" id='img1'/><br/> <img src="http://image15-c.poco.cn/mypoco/myphoto/20141226/23/6491218420141226234200099_640.jpg?1024x855_120" id='img2' /> </body> </html>
運行結果: