Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attachEvent / addEventListener to Window onload / load - preferred way

I have a script that starts when the page loads and I had been using this code below to start it:

if (window.addEventListener) {
  window.addEventListener('load', otherRelatedParts, false);
}
else if (window.attachEvent) {
  window.attachEvent('onload', otherRelatedParts );
}

but today I tried with a self invoking function like this:

(function() {
otherRelatedParts();
}())

It seems to work, in all browsers and is less code. Is this the preferred way to add events to the window load?

like image 249
bryan sammon Avatar asked Mar 25 '11 18:03

bryan sammon


2 Answers

Your self invoking function will execute earlier than window.onload. It will execute at the moment the browser reads it. In most cases it actually does not make any difference so you can use it this way. Window.load is normally raised when all objects (images, JavaScript files etc) have been downloaded. $(document).ready() triggers earlier than window.onload - when the DOM is ready for manipulation.

like image 147
Atanas Korchev Avatar answered Nov 14 '22 10:11

Atanas Korchev


I guess the above if clause is written to cover some cross browser issues. You should factor these things out of your code.

As other people have done this before, you might as well use some library as jQuery. You should look for .ready() there.

like image 35
mkluwe Avatar answered Nov 14 '22 12:11

mkluwe