重新整理javascript的domReady函数(更新至IE9)(转)
重新整理javascript的domReady函数(更新至IE9)
http://www.joy-studio.com/frontend-develop/rewrite-javascript-domready-function.html
实践之:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>domReady</h1>
<div id="J_testDiv">
</div>
<script type="text/javascript">
/*
* domReady
* Cross Browsers DOMContentLoaded Event Method
* @param fn {Function} the DOMContentLoaded Callback Function
* @author Doomin | http://joy-studio.com
* @updata 2011-03-24
*/
var domReady = (function(){
var doc = document, branch = document.addEventListener ? 'w3c' : 'ie678'; //branching flag
var _domReady = {
// When _domReady.done is true,all 'fn' will be invoked immediately.
done: false,
// The stack which all functions will be pushed into
fn: [],
// push callback functions
push: function(fn){
if (!_domReady.done) {
// only bind once
if (_domReady.fn.length === 0) {
_domReady.bind();
}
_domReady.fn.push(fn);
}
else {
fn();
}
},
// The Real DOMContentLoaded Callback Function
ready: function(){
// Flag DOMContentLoaded Event was Done over
_domReady.done = true;
var fn = _domReady.fn;
for (var i = 0, l = fn.length; i < l; i++) {
fn[i]();
}
_domReady.unbind();
_domReady.fn = null;
},
bind: {
w3c: function(){
doc.addEventListener('DOMContentLoaded', _domReady.ready, false);
},
//IE的监听方法参考了这篇文章:http://javascript.nwbox.com/IEContentLoaded/
ie678: function(){
var done = false, // only fire once
init = function(){
if (!done) {
done = true;
_domReady.ready();
}
};
// polling for no errors
(function(){
try {
// throws errors until after ondocumentready
doc.documentElement.doScroll('left');
}
catch (e) {
setTimeout(arguments.callee, 20);
return;
}
// no errors, fire
init();
})();
// trying to always fire before onload
doc.onreadystatechange = function(){
if (doc.readyState == 'complete') {
doc.onreadystatechange = null;
init();
}
};
}
}[branch],
unbind: {
w3c: function(){
doc.removeEventListener('DOMContentLoaded', _domReady.ready, false);
},
ie678: function(){/* Nothing to do */
}
}[branch]
};
return _domReady.push;
})();
function addP(txt){
var div = document.getElementById('J_testDiv');
var p = document.createElement('p');
var text = document.createTextNode(txt + ' > ' + new Date().getTime());
p.appendChild(text);
div.appendChild(p);
}
//在DOMContentLoaded之前, 第一次调用domReady
domReady(function(){
addP('DOMContentLoaded被触发, 执行第一个回调函数');
});
//在DOMContentLoaded之前, 第二次调用domReady
domReady(function(){
addP('执行第二个回调函数');
});
//延迟2秒, 确保在DOMContentLoaded触发以后调用domReady
setTimeout(function(){
domReady(function(){
addP('2秒后,第三个回调函数被立即执行');
});
}, 2000);
</script>
</body>
</html>