javascript 의 domReady 함 수 를 다시 정리 합 니 다 (IE9 로 업데이트)

24946 단어 JavaScript
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>

좋은 웹페이지 즐겨찾기