window.onload 必須等頁面所有資源(含圖片)都下載完才觸發,但我們通常更希望 DOM 一解析完成就執行腳本。多數主流瀏覽器(Firefox 3+、Opera 9+、Safari 3+、Chrome 2+)都提供了對應事件:
document.addEventListener("DOMContentLoaded", init, false);
最早的變通做法是寫入一個 defer 的 script 標籤,再監聽它的 readyState:
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
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
}
};
/*@end @*/
其後 Diego Perini 提出利用 doScroll() 模擬 DOMContentLoaded 的做法,jQuery、YUI 等主流框架基本都採用這條路。原理是:當 DOM 準備好之後,對 documentElement 呼叫 doScroll 才不會拋錯;否則會不斷失敗,因此可以用「反覆嘗試直到成功」來判斷時機。
需要注意的是,某些方法(如 doScroll)要求初始文件已被完全載入,因此若你的初始化邏輯用到它們,就得等 ondocumentready 之後再執行。
/*
* IEContentLoaded.js
* Author: Diego Perini (diego.perini at gmail.com) NWBOX S.r.l.
* Summary: DOMContentLoaded emulation for IE browsers
* License: GPL/CC
*/
// @w window reference
// @fn function reference
function IEContentLoaded (w, fn) {
var d = w.document, done = false,
// only fire once
init = function () {
if (!done) {
done = true;
fn();
}
};
// polling for no errors
(function () {
try {
// throws errors until after ondocumentready
d.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
// no errors, fire
init();
})();
// trying to always fire before onload
d.onreadystatechange = function() {
if (d.readyState == 'complete') {
d.onreadystatechange = null;
init();
}
};
}
jQuery 1.3.2 的做法是:在 IE 且非 iframe 的情況下持續輪詢 doScroll。
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// https://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
YUI 2.7.0 則用 setInterval 搭配 doScroll:
if (EU.isIE) {
// Process onAvailable/onContentReady items when the DOM is ready.
YAHOO.util.Event.onDOMReady(
YAHOO.util.Event._tryPreloadAttach,
YAHOO.util.Event, true);
var n = document.createElement('p');
EU._dri = setInterval(function() {
try {
// throws an error if doc is not ready
n.doScroll('left');
clearInterval(EU._dri);
EU._dri = null;
EU._ready();
n = null;
} catch (ex) {}
}, EU.POLL_INTERVAL);
}
至於舊版 Safari(3.0 之前),John Resig 提供了輪詢 readyState 的解法:
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init(); // call the onload handler
}
}, 10);
}
// form JQuery 1.3.2
// ensure firing before onload, maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
最後提醒一句:這些都是為了相容 IE8 及以下版本而生的技藝。當你的專案已不再支援舊版 IE,直接寫 document.addEventListener("DOMContentLoaded", ...) 就好,不必背負這一整包歷史包袱。