33

This is the code i used in my page,

if (window.addEventListener) {
   window.addEventListener("load", createIframe, false);            
}
else if (window.attachEvent) {
   window.attachEvent("onload", createIframe);            
}
else {
   window.onload = createIframe;           
}

Please explain me that where my createIframe funtion get called? and what is the difference between addEventListener and attachEvent? and what is the different between load and onload? totally confused to find difference between addEventLisener with load and attachEvent with onload

2

1 Answer 1

57

Quick answer: you have to use attachEvent if your browser returns undefined == window.addEventListener. Thing is the former is a non-standard JS function implemented in IE8 and previous versions, while addEventListener is supported by IE9+ (and all the other browsers).

So the big question is: are you gonna support IE8-?

Margin note: window.onload = whatever will override any attached event listeners. This is why addEventListener is used: to add a function to the event's stack, instead of overwriting it.

1
  • 1
    Can babel be used to transpile addEventListener for older browsers? The preset-env doesn't seem to do it.. Jun 20, 2020 at 12:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.