简体   繁体   中英

DOMContentLoaded event does not fire

I wanted to try DOMContentLoaded event of javascript for IE. But that event does not fire. Is this not supported on IE. Kindly help with this. Upon googling i didn't find much help. I want to try this in javascript and not jquery. Kindly help with this.

DOMContentLoaded is supported in IE9 and above and all other modern browsers.

There are work-arounds for early versions of IE using onreadystatechange . 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.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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