上次写过 《模拟兼容性的 addDOMLoadEvent 事件》,昨天抽时间整理成了 domReady 函数。
使用非常方便:
domReady(function () {
// Dom is loaded! You can do anything!
});
测试案例: [blank.github.com]
代码如下(注释较为详尽,就不再说明了):
/**
* domready.js - Specify a function to execute when the DOM is fully loaded.
* Copyright (c) 2011 Blank Zheng (blankzheng@gmail.com)
* [www.planabc.net] */
(function (doc, win) {
var isReady = 0,
isBind = 0,
fns = [],
testEl = doc.createElement('p'),
bindReady,
init;
win.domReady = function(fn){
bindReady(fn);
if (isReady) {
fn();
} else {
fns.push(fn);
}
};
bindReady = function (){
if(isBind) return;
isBind = 1;
// Catch cases where domReady is called after the browser event has already occurred.
// readyState: "uninitalized"、"loading"、"interactive"、"complete" 、"loaded"
if(doc.readyState === "complete") {
init();
} else if (doc.addEventListener) {
doc.addEventListener("DOMContentLoaded", function () {
doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
init();
}, false);
win.addEventListener("onload", init, false);
} else if(doc.attachEvent) {
// In IE, ensure firing before onload, maybe late but safe also for iframes.
doc.attachEvent("onreadystatechange", function() {
if (doc.readyState === "complete") {
doc.detachEvent("onreadystatechange", arguments.callee);
init();
}
});
win.attachEvent("onload", init);
// If IE and not a frame, continually check to see if the document is ready.
if(testEl.doScroll && win == win.top){
doScrollCheck();
}
}
};
// Process items when the DOM is ready.
init = function () {
isReady = 1;
// Make sure body exists, at least, in case IE gets a little overzealous.
// This is taked directly from jQuery's implementation.
if (!doc.body) {
setTimeout(init, 10);
return;
}
for (var i = 0, l = fns.length; i
如果平时做一些简单测试,可以使用下面 MINI 的 domReady 函数:
function domReady(fn) {
// "uninitalized"、"loading"、"interactive"、"complete" 、"loaded"
/in/.test(document.readyState) ? window.setTimeout(function() { domReady(fn); }, 10) : fn();
}