---
title: "DOMContentLoaded事件"
author: "wayne173"
date: "2011-02-14T16:18:33Z"
tags: []
categories: ["Web前端"]
slug: "domcontentloaded"
draft: false
lastmod: "2011-02-14T16:18:33Z"
id: 906030
url: "https://wayne173.iteye.com/blog/906030"
---

今天查看百度空间源代码，发现多了个util.js文件，打开看看。里面里面定义了addDOMLoadEvent。这是干什么用的？

仔细查看代码，发现在Mozilla添加了DOMContentLoaded事件，这个在以前一直没有用过。                    if (document.addEventListener)  
                        document.addEventListener("DOMContentLoaded", init, false);

好久就是为了兼容实现DOMContentLoaded事件。

网上找了点有关DOMContentLoaded的资料拿来看看。

DOMContentLoaded是firefox下特有的Event, 当所有DOM解析完以后会触发这个事件。  
    与DOM中的onLoad事件与其相近。但onload要等到所有页面元素加载完成才会触发, 包括页面上的图片等等。  
    如果页面的图片很多的话, 从用户访问到onload触发可能需要较长的时间, 而在Ajax运用中, 常常需要在onload中加入许多初始化的动作, 如果由于网络问题引起的图片加载过慢( 见: Ajax优化(2) -- lazierLoad img && js), 则必然影响用户的体验。  
    在这种情况下firefox的DOMContentLoaded事件, 恰恰是我们需要的。

    目前,跨平台的DOMContentLoaded的解决方案有很多, 比如jQuery, Prototype...等等, 其实现原理大同小异.

    在项目中, 我使用了Prototype工具, 以往调用初始化的方法是:

Event.observe(window, "load", init);

    现在有了DOMContentLoaded, 可以替换成如下的方法:

document.observe('contentloaded', init);

    最新的prototype中自定义事件已经重新命名, 使用"dom:loaded" 代替了 “contentloaded”.

document.observe('dom:loaded', init);

附:

   [Andrea Giammarchi](http://webreflection.blogspot.com/) 的OnContent函数提供了一个跨平台的DOMContentLoaded的解决方案[My DOMContentLoaded Final Solution](http://webreflection.blogspot.com/search?q=onContent)

文件名称：DOMContentLoaded.js

01. function onContent ( f ) {
02. var a = onContent,
03. b = navigator . userAgent ,
04. d = document ,
05. w = window ,
06. c = "onContent" ,
07. e = "addEventListener" ,
08. o = "opera" ,
09. r = "readyState" ,
10. s = "&lt;scr" . concat ( "ipt defer src='//:' on" , r, "change='if(this." , r, "==\\"complete\\"){this.parentNode.removeChild(this);" , c, "." , c, "()}'&gt;&lt;/scr" , "ipt&gt;" ) ;
11. a\[ c] = ( function ( o) {
12. return function ( ) {
13. a\[ c] = function ( ) { } ;
14. for ( a = arguments . callee ; ! a. done; a. done = 1) f( o ? o( ) : o)
15. }
16. } ) ( a\[ c] ) ;
17. if ( d\[ e ] ) d\[ e ] ( "DOMContentLoaded" , a\[ c] , false ) ;
18. if ( / WebKit| Khtml/ i. test ( b) | | ( w\[ o] & & parseInt ( w\[ o] . version ( ) ) &lt; 9) ) ( function ( ) { / loaded | complete / . test ( d\[ r] ) ? a\[ c] ( ) : setTimeout ( arguments . callee , 1)
19. } ) ( ) ;
20. else if ( / MSIE/ i. test ( b) ) d. write ( s) ;
21. } ;

 

util.js：

addDOMLoadEvent = (function(){  
        // create event function stack  
        var load\_events = \[],  
            load\_timer,  
            script,  
            done,  
            exec,  
            old\_onload,  
            init = function () {  
                done = true;  
                // kill the timer  
                clearInterval(load\_timer);

                // execute each function in the stack in the order they were added  
                while (exec = load\_events.shift())  
                    setTimeout(exec, 10);  
                if (script) script.onreadystatechange = '';  
            };

            return function (func) {  
                // if the init function was already ran, just run this function now and stop  
                if (done) return func();

                if (!load\_events\[0]) {  
                    // for Mozilla/Opera9  
                    if (document.addEventListener)  
                        document.addEventListener("DOMContentLoaded", init, false);

                    // for Internet Explorer

                    [/\*@cc\_on]() @\*/  
                    [/\*@if]() (@\_win32)  
                        document.write("&lt;script id=\_\_ie\_onload defer src=//0&gt;&lt;\\/scr"+"ipt&gt;");  
                        script = document.getElementById("\_\_ie\_onload");  
                        script.onreadystatechange = function() {  
                            if (this.readyState == "complete")  
                                init(); // call the onload handler  
                        };  
                    [/\*@end]() @\*/

                    // for Safari  
                    if (/WebKit/i.test(navigator.userAgent)) { // sniff  
                        load\_timer = setInterval(function() {  
                            if (/loaded|complete/.test(document.readyState))  
                                init(); // call the onload handler  
                        }, 10);  
                    }

                    // for other browsers set the window.onload, but also execute the old window.onload  
                    old\_onload = window.onload;

                    window.onload = function() {  
                        init();  
                        if (old\_onload) old\_onload();  
                    };  
                }

            load\_events.push(func);  
        }  
})();

function insertWBR(string, step){  
    var textarea = document.createElement('TEXTAREA');  
    textarea.innerHTML = string.replace(/&lt;/g,"&lt;").replace(/&gt;/g,"&gt;");  
    string = textarea.value;

    var step = (step || 5), reg = new RegExp("([\\\\S]() {" + step + "})", "gi");  
    return string.replace(/(&lt;\[^&gt;]+&gt;)/gi,"$1&lt;wbr/&gt;").replace(/(&gt;|^)(\[^&lt;]+)(&lt;|$)/gi, function(a,b,c,d){  
        if(c.length &lt; step) return a;  
        return b + c.replace(reg, "$1&lt;wbr/&gt;") + d;  
    });  
}