欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DOMContentLoaded事件 博客分类: Javascript webkitC#C++CIE 

程序员文章站 2024-03-01 15:09:22
...

今天查看百度空间源代码,发现多了个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 的OnContent函数提供了一个跨平台的DOMContentLoaded的解决方案My DOMContentLoaded Final Solution

文件名称:DOMContentLoaded.js
  1. function onContent ( f ) {
  2.     var a = onContent,
  3.      b = navigator . userAgent ,
  4.      d = document ,
  5.      w = window ,
  6.      c = "onContent" ,
  7.     e = "addEventListener" ,
  8.      o = "opera" ,
  9.      r = "readyState" ,
  10.      s = "<scr" . concat ( "ipt defer src='//:' on" , r, "change='if(this." , r, "==\"complete\"){this.parentNode.removeChild(this);" , c, "." , c, "()}'></scr" , "ipt>" ) ;
  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 ( ) ) < 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("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                        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(/</g,"&lt;").replace(/>/g,"&gt;");
    string = textarea.value;

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