跨浏览器 Dom 就绪
我继承了这段代码,它似乎不是最优的,而且可能不正确,因为它在窗口和文档对象上添加了事件侦听器。但是,除黑莓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);
I inherited this piece of code and it seems sub-optimal 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想知道它是如何完成的或查看实现它的方法。我建议您看看迭戈·佩里尼 (Diego Perini) 的作品。他的工作和方法被用于许多 DOM 库,包括 jQuery。不幸的是,这家伙似乎没有得到太多的信任。他是 try/catch 轮询方法的先驱者,这使得当 IE 加入其中时跨浏览器 dom 加载事件成为可能。
https://github.com/dperini/ContentLoaded/blob/master/src/contentloaded.js< /a>
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
如果你想使用纯javascript,你可以使用以下跨浏览器函数(来源(俄语):http://javascript.ru/unsorted/top-10-functions)
用法:
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)
Usage:
就我个人而言,我会使用 jQuery 来实现此目的。
jQuery 旨在处理文档就绪状态的各种不同浏览器实现。
使用 jQuery,上面的代码将如下所示:
Personally I'd use jQuery for this.
jQuery is designed to handle the variety of different browser implimentations of the document ready state.
Using jQuery your above code would look like: