首先要明確兩個概念
1.window.onload:頁面加載完畢,頁面內所有組件(圖片等)都可用。
2.dom 加載:指文檔對象模型加載完畢,要先于window.onload事件。
可以看出,當頁面包含大量組件(特別是圖片)的情形下,以上兩種加載的時間相隔將會很長,這時判斷dom何時加載完成就顯得特別重要
頁面的一些組件(css,image,flash)不會導致頁面的DOM未構建完成。只有JS會阻塞頁面的DOM節點的構建
function init() {
// 如果該函數被調用多次,直接返回
if (arguments.callee.done) return;
//
arguments.callee.done = true;
// 清除對safari設置的定時器
if (_timer) clearInterval(_timer);
alert(document.getElementById(“test”).id);
};
// firefox和opera9.0
if (document.addEventListener) {
document.addEventListener(“DOMContentLoaded”, init, false);
}
//ie
document.write(“<script id=__ie_onload defer src=javascript:void(0)></script>”);
var script = document.getElementById(“__ie_onload”);
script.onreadystatechange = function() {
if (this.readyState == “complete”) {
init(); // call the onload handler
}
};
//Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
//其它瀏覽器直接用window.onload事件
window.onload = init;
來源:http://www.wellpeter.com/?p=162