跨浏览器Dom Ready [英] Cross Browser Dom Ready

查看:88
本文介绍了跨浏览器Dom Ready的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

        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);


推荐答案

如果你想知道它是怎么做的或者看到一个这样做的方式。我建议看看Diego Perini的作品。他的工作和方法被用在许多DOM库中,包括jQuery。不幸的是,这家伙似乎没有得到太多的信任。他是开创了try / catch轮询方法的人,当IE投入混合时,这使得跨浏览器dom加载事件成为可能。

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.

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

这篇关于跨浏览器Dom Ready的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆