简体   繁体   English

DOMContentLoaded事件不会触发

[英]DOMContentLoaded event does not fire

I wanted to try DOMContentLoaded event of javascript for IE. 我想尝试IE的javascript的DOMContentLoaded事件。 But that event does not fire. 但是该事件不会触发。 Is this not supported on IE. IE不支持此功能吗? Kindly help with this. 请对此提供帮助。 Upon googling i didn't find much help. 谷歌搜索后,我没有找到太多帮助。 I want to try this in javascript and not jquery. 我想尝试使用javascript而不是jquery。 Kindly help with this. 请对此提供帮助。

DOMContentLoaded is supported in IE9 and above and all other modern browsers. IE9及更高版本和所有其他现代浏览器均支持DOMContentLoaded

There are work-arounds for early versions of IE using onreadystatechange . 对于使用onreadystatechange的IE早期版本,有一些变通办法。 You can see a full cross-browser, plain javascript content loaded detection function here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it which you can either use as is or you can borrow concepts from the code. 您可以在此处看到完整的跨浏览器,简单的javascript内容加载检测功能: 纯JavaScript等效于jQuery的$ .ready()如何在页面/ dom准备就绪时调用函数 ,您可以按原样使用,也可以可以从代码中借用概念。

The basic idea is that you use DOMContentLoaded in modern browsers and in older versions of IE you use onreadystatechange with a fallback to window onload . 基本思想是,在现代浏览器中使用DOMContentLoaded ,在较旧版本的IE中,您使用onreadystatechange并回退到window onload The first one to fire is the earliest moment that the document is safe to query and modify. 首先触发的是文档可以安全查询和修改的最早时刻。

The crux of the above linked code is this logic: 上面链接的代码的症结在于这种逻辑:

        // otherwise if we don't have event handlers installed, install them
        if (document.addEventListener) {
            // first choice is DOMContentLoaded event
            document.addEventListener("DOMContentLoaded", ready, false);
            // backup is window load event
            window.addEventListener("load", ready, false);
        } else {
            // must be IE
            document.attachEvent("onreadystatechange", readyStateChange);
            window.attachEvent("onload", ready);
        }

It is also possible that you are registering for the event AFTER the document is already ready. 文档准备就绪后,也有可能要注册该事件。 If that's the case, your event handler will never get called because the event already occurred. 如果是这样,您的事件处理程序将永远不会被调用,因为该事件已经发生。 You can check the document state before installing the event handler to see if it is already ready like this: 您可以在安装事件处理程序之前检查文档状态,以查看它是否已经准备就绪,如下所示:

if (document.readyState === "complete") {

Again, the full logic is shown here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it 同样,这里显示了完整的逻辑: 纯JavaScript等效于jQuery的$ .ready()如何在页面/ dom准备就绪时调用函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM