There are several reasons it might not fire:
- It has already fired (before you attached the event handler) and you missed it.
- You're running an older version of IE that doesn't support the
DOMContentLoaded
event.
- 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.
- 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.