javascript 跨浏览器 Dom 就绪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6902280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:17:22  来源:igfitidea点击:

Cross Browser Dom Ready

javascriptjavascript-eventsonload-event

提问by VinnyD

I inherited this piece of code and it seems suboptimal and possibly incorrect since it's adding event listeners on both the window and document objects. However, it is working properly except for blackberry 5.0. Can someone explain if all this is set up correctly or if there are any recommendations to make it better and/or more streamlined?

我继承了这段代码,它似乎不是最理想的,而且可能不正确,因为它在窗口和文档对象上都添加了事件侦听器。但是,除了黑莓 5.0 之外,它都可以正常工作。有人可以解释一下所有这些设置是否正确,或者是否有任何建议可以使其更好和/或更简化?

        if (document.readyState === "complete") 
            callback();
        else if (document.addEventListener) 
        {
            document.addEventListener("DOMContentLoaded",callback,false);
            window.addEventListener("load",callback,false);
        }
        else if(window.attachEvent) 
        {
            document.attachEvent("onreadystatechange", callback);
            window.attachEvent("onLoad",callback);
        } else
            setTimeout(callback,2000);

回答by chjj

If you want to know how it's done or see a way of doing it. I recommend looking at Diego Perini's work. His work and methods are used in many DOM libraries, including jQuery. The guy doesn't seem to get much credit unfortunately. He is the one who pioneered the try/catch polling method, which is what makes cross-browser dom loaded events possible when IE is thrown into the mix.

如果您想知道它是如何完成的,或者想了解一种方法。我建议看看 Diego Perini 的作品。他的工作和方法被用于许多 DOM 库,包括 jQuery。不幸的是,这家伙似乎并没有得到多少荣誉。他是 try/catch 轮询方法的先驱,这使得跨浏览器 dom 加载事件在 IE 混入时成为可能。

https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js

https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js

回答by VIK

If you want to use pure javascript, you can use thу following cross-browser function (source (in Russian): http://javascript.ru/unsorted/top-10-functions)

如果您想使用纯 javascript,您可以使用以下跨浏览器功能(来源(俄语):http: //javascript.ru/unsorted/top-10-functions

function bindReady(handler){
    var called = false     
    function ready() {
        if (called) return
        called = true
        handler()
    }     
    if ( document.addEventListener ) {
        document.addEventListener( "DOMContentLoaded", function(){
            ready()
        }, false )
    } else if ( document.attachEvent ) { 
        if ( document.documentElement.doScroll && window == window.top ) {
            function tryScroll(){
                if (called) return
                if (!document.body) return
                try {
                    document.documentElement.doScroll("left")
                    ready()
                } catch(e) {
                    setTimeout(tryScroll, 0)
                }
            }
            tryScroll()
        }
        document.attachEvent("onreadystatechange", function(){     
            if ( document.readyState === "complete" ) {
                ready()
            }
        })
    }
    if (window.addEventListener)
        window.addEventListener('load', ready, false)
    else if (window.attachEvent)
        window.attachEvent('onload', ready)
    /*  else  // use this 'else' statement for very old browsers :)
        window.onload=ready
    */
}
readyList = []      
function onReady(handler) {  
    if (!readyList.length) { 
        bindReady(function() { 
            for(var i=0; i<readyList.length; i++) { 
                readyList[i]() 
            } 
        }) 
    }   
    readyList.push(handler) 
}

Usage:

用法:

onReady(function() {
  // ... 
})

回答by Jamie Dixon

Personally I'd use jQueryfor this.

我个人会为此使用jQuery

jQuery is designed to handle the variety of different browser implimentations of the document ready state.

jQuery 旨在处理文档就绪状态的各种不同浏览器实现。

Using jQuery your above code would look like:

使用 jQuery,您上面的代码将如下所示:

$(callback);