0

Currently, I wish to capture onLoad event.

I was wondering, what is the differnce among

if (window.addEventListener){
    window.addEventListener('load', func1)
} else {
    window.attachEvent('onload', func1)
}

var oldOnload1 = window.onload;
window.onload=function(){
    oldOnload1 && oldOnload1();
    func1();
}

Both methods works as expected. May I know, which method is a better way?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • addEventListener is definitely more flexible and less prone to screw ups - but that's just a matter of opinion. Your second example is messy as hell, valid, but ugly :p – Jaromanda X Jan 10 '17 at 02:55
  • This has been done to death, if not on SO then on the web. See [*Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events*](http://stackoverflow.com/questions/3763080/javascript-add-events-cross-browser-function-implementation-use-attachevent-add). The biggest issues are that *attachEvent* doesn't set the event target as *this*, nor pass the *event* object to the listener (though it's typically available as *window.event* where *addEventListener* isn't supported). Google *attachEvent* (and beware rubbish implementations). ;-) – RobG Jan 10 '17 at 03:13
  • There is no reason to use `attachEvent` except to support archaic versions of IE. You are strongly recommended to us `addEventListener` instead of assigning the `onload` attribute, since the `onload` attribute could be overwritten by some other code, whereas a listener set up with `addEventListener` will remain safely in place until it's explicitly removed. –  Jan 10 '17 at 03:48

0 Answers0