Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Code:

if (document.addEventListener) {
   document.addEventListener("DOMContentLoaded", init, false);
}
else {
   document.attachEvent("onDOMContentLoaded", init);
}
like image 977
Cedric Krause Avatar asked Jul 23 '14 07:07

Cedric Krause


2 Answers

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();
}
like image 118
gkweb Avatar answered Nov 09 '22 21:11

gkweb


There are several reasons it might not fire:

  1. It has already fired (before you attached the event handler) and you missed it.
  2. You're running an older version of IE that doesn't support the DOMContentLoaded event.
  3. There's some sort of script error before these lines of code so these lines of code are not actually executed and thus the event handler is never actually registered.
  4. You're trying to do this on an embedded iFrame and may not have the correct document for the iFrame (some browsers can switch the document when loading external source).

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.

like image 20
jfriend00 Avatar answered Nov 09 '22 20:11

jfriend00