I have the following code to attach a function to the DOMContentLoaded
event, but the function is never called in Internet Explorer 11
Code:
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
else {
document.attachEvent("onDOMContentLoaded", init);
}
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.
A simple solution for this is to add a check to the document 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.
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();
}
There are several reasons it might not fire:
DOMContentLoaded
event.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.
You can check to see if document.readyState === "complete"
to see if it has already fired.
And, in versions of IE before IE9 where you would need attachEvent
, IE doesn't support DOMContentLoaded
so your else branch would not work. You would have to use different detection methods in those older versions of 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With