DOMContentLoaded事件在大多數情況下去替代window.onload事件,因爲window.onload事件必須要等待頁面所有元素都下載完後才執行。而DOMContentLoaded事件是在DOM樹建成時觸發,因此要比onload事件快得多,它是W3C推薦的標準事件。ff,opera已經支持該事件,但IE8還都不支持。因此IE要採用doScroll事件來實現ready,原理是doScroll要在DOM樹形成後才能操作。
在IE的情況下,用doScroll事件來判斷:
<script type="text/javascript">
//<![CDATA[
var fireDOMReadyEvent = function(){
window.clearInterval(timer);
alert('DOM content loaded');
if (!!window.ActiveXObject && window == top){ //也有人用 document.attachEvent 來判斷是IE的,問題:如果這個頁面是嵌在frame中的,如何使用ready呢?
var timer = null;
timer = setInterval(function(){
try{
document.documentElement.doScroll('left');
fireDOMReadyEvent();
}catch(e){};
});
}
}
//]]>
</script>
跨瀏覽器的方案:
// Mozilla,opera,webkit 支持DOMContentLoaded事件
if(docuemnt.addEventListener && !jQuery.browser.opera)
//直接使用事件回調即可
document.addEventListener('DOMContentLoaded',xxx,false);
//如果是IE並且不是嵌在frame中就需要不斷檢測文檔是否加載完畢
if(!!window.ActiveXObject && window == top ){
(function(){
try{
document.documentElement.doScroll("left");
}catch(error){
setTimeout(arguments.callee,0);
return;
}
//在這裏可以調用等待運行的函數
})();
}
//opera的DOMContentLoaded事件發生後,其css也是是還不能完全可用的,所以要特殊處理,就是判斷每個css的tag都是不是可用了
if(/(opera)(?:.*version)?[ \/]([\w.]+)/i.test(navigator.userAgent)){
document.addEventListener("DOMContentLoader",function(){
for (var i = 0;i<document.styleSheets.length;i++){
if(document.styleSheet.disabled){
setTimeout(argument.callee,0);
return;
}
//在這裏可以調用等待運行的函數
}
},false);
}
//safari中document.readyState的狀態爲loaded或complete時,css文件引入還未能確定是不是解析完了的,所以要判斷其css文件數目
if(/WebKit/i.test(navigator.userAgent)){
var numStyles;
(function(){
if(document.readyState != "loaded" && document.readyState != "complete"){
setTimeout(argument.callee,0);
return;
}
if(numStyles === undefined){
numStyles = jQuery("style,link[rel=stylesheet]").length;
}
if(document.styleSheets.length != numStyles){
setTimeout(argument.callee,0);
return;
}
//在這裏可以調用等待運行的函數
})();
//最後,如果上面的hack都不支持的話,就用onload事件
window.onload = function(){
//在這裏可以調用等待運行的函數
}
}
參考: