[英]Javascript DOMContentLoaded event not firing in Internet Explorer
I have the following code to attach a function to the DOMContentLoaded
event, but the function is never called in Internet Explorer 11我有以下代码将函数附加到
DOMContentLoaded
事件,但在 Internet Explorer 11 中从未调用该函数
Code:代码:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
else {
document.attachEvent("onDOMContentLoaded", init);
}
There are several reasons it might not fire:它可能不会触发有几个原因:
DOMContentLoaded
event.DOMContentLoaded
事件的旧版 IE。 To check for script errors, you should open the debug console in IE (press F12) and look at the console to see if any script errors are being reported.要检查脚本错误,您应该在 IE 中打开调试控制台(按 F12)并查看控制台以查看是否报告了任何脚本错误。
You can check to see if document.readyState === "complete"
to see if it has already fired.您可以检查
document.readyState === "complete"
是否已经触发。
And, in versions of IE before IE9 where you would need attachEvent
, IE doesn't support DOMContentLoaded
so your else branch would not work.而且,在 IE9 之前的 IE 版本中,您需要
attachEvent
,IE 不支持DOMContentLoaded
因此您的 else 分支将不起作用。 You would have to use different detection methods in those older versions of IE.您将不得不在那些旧版本的 IE 中使用不同的检测方法。
You can see a well tested, cross-browser, plain javascript function for getting notified when the document is ready here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it .您可以在这里看到一个经过良好测试的跨浏览器纯 javascript 函数,用于在文档准备好时获得通知: 纯 JavaScript 相当于 jQuery 的 $.ready() 如何在页面/dom 准备好时调用函数。
To break this down with a workable example see below.用一个可行的例子来分解这个,见下文。 The issue I found was that
DOMContentLoaded
won't fire for javascript
unless the event is created inline within the document itself.我发现的问题是
DOMContentLoaded
不会为javascript
触发,除非事件是在文档本身内内联创建的。
A simple solution for this is to add a check to the document readyState
.一个简单的解决方案是向文档
readyState
添加一个检查。 If it's still loading - create the event because it's possible for DOMContentLoaded
to fire - Otherwise just load immediately because DOM is ready.如果它仍在加载 - 创建事件,因为
DOMContentLoaded
可能会触发 - 否则只需立即加载,因为 DOM 已准备就绪。
var load = function () {
console.log('I will always load, woohoo');
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', load); // Document still loading so DomContentLoaded can still fire :)
} else {
load();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.