I need to write a piece of code that will attach a listener to selected event, and that will work in any popular browser, in any version of it. After doing some searching I came out with following function:
function addListener(event, thefunction)
{
if(window.addEventListener)
{
//All browsers, except IE before version 9.
window.addEventListener(event, thefunction, false);
}
else if(window.attachEvent)
{
//IE before version 9.
window.attachEvent(event, thefunction);
}
}
Quite simple and seems to be self-explanatory.
There might be some problem with DOMContentLoaded event, as none version of IE (AFAIK) does recognizes it, and developers are obligated to use onreadystatechange instead. Solving this problem also seems to be fairly simple, until Internet Explorer 9. You had to write only an extra line in else if(window.attachEvent):
event = (event == 'DOMContentLoaded') ? 'onreadystatechange' : "on" + event;
This part was always fired in any version of Internet Explorer and this line provided a simple translation of event name, so a correct one was always used.
But what about Internet Explorer 9 (and above)? In which Microsoft decided that it will drop attachEvent in favor of addEventListener. But doesn’t changed onreadystatechange into DOMContentLoaded.
I can’t use above line in window.addEventListener part, because this will rewrite DOMContentLoaded into onreadystatechange event even for other browsers and fail there, as they use DOMContentLoaded.
So, does the only way to solve this problem, is to add browser detection (type and version) to window.addEventListener part and if it detects that script is dealing with IE 9 or above, it will rewrite event name from DOMContentLoaded to onreadystatechange (and supplement other events name with on, required for IE), and in case of other browsers, will leave event name not changed?
Or maybe I’m wrong, because as I just tested, neither DOMContentLoaded nor onreadystatechange is being fired in my IE 8 (first one fires correctly in Firefox / Chrome).
And what about jQuery’s .on() function (or similar)? Does anyone knows, if it supports cross-browser attaching of DOMContentLoaded, so I can be sure that this specific kind of event will be catch by my script, no matter, in which browser or it’s version I’m using?
DOMContentLoadedis natively supported in IE9 and above and can be attached through the W3C-standardaddEventListenermethod which was also implemented in IE9:That will work in all modern browsers and IE from version 9 and up.
jQuery 1.x is compatible with IE6+ and any other update-to-date browser. jQuery can hook a DOM ready event cross-browser by shimming support for IE6-8 through the DOM ready handler:
.on()provides event delegation, but that’s rather unrelated to the question.