Created
June 3, 2012 19:30
-
Star
(155)
You must be signed in to star a gist -
Fork
(27)
You must be signed in to fork a gist
-
-
Save eirikbacker/2864711 to your computer and use it in GitHub Desktop.
addEventListener polyfill for IE6+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//addEventListener polyfill 1.0 / Eirik Backer / MIT Licence | |
(function(win, doc){ | |
if(win.addEventListener)return; //No need to polyfill | |
function docHijack(p){var old = doc[p];doc[p] = function(v){return addListen(old(v))}} | |
function addEvent(on, fn, self){ | |
return (self = this).attachEvent('on' + on, function(e){ | |
var e = e || win.event; | |
e.preventDefault = e.preventDefault || function(){e.returnValue = false} | |
e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true} | |
fn.call(self, e); | |
}); | |
} | |
function addListen(obj, i){ | |
if(i = obj.length)while(i--)obj[i].addEventListener = addEvent; | |
else obj.addEventListener = addEvent; | |
return obj; | |
} | |
addListen([doc, win]); | |
if('Element' in win)win.Element.prototype.addEventListener = addEvent; //IE8 | |
else{ //IE < 8 | |
doc.attachEvent('onreadystatechange', function(){addListen(doc.all)}); //Make sure we also init at domReady | |
docHijack('getElementsByTagName'); | |
docHijack('getElementById'); | |
docHijack('createElement'); | |
addListen(doc.all); | |
} | |
})(window, document); |
Fine work, thank you. There may be an issue with line 11:
fn.call(self, e);
In case that fn
is an empty object. When running IE11 in emulation mode for IE8, then it reports that this method is unavailable:
Das Objekt unterstützt diese Aktion nicht.
Adding a condition helps:
if ("call" in fn) fn.call(self, e);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original version, it occurs an error while use it with jQuery in lte IE 8 after bundled via WebPack with jQuery. It fills only
addEventListener
. When jQuery loaded then detect eventListener via onlyaddEventListener
then jQuery try to useremoveEventListener
that you can see on Ready.js in jQuery 1.12.4.@nbouvrette Could I sure to use your version for "DOMContentLoaded" also?