10

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?

Joe Frambach
  • 25,568
  • 9
  • 65
  • 95
bryan sammon
  • 6,441
  • 12
  • 35
  • 44

2 Answers2

11

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.

Atanas Korchev
  • 30,192
  • 8
  • 55
  • 90
1

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.

mkluwe
  • 3,321
  • 1
  • 19
  • 40
  • 17
    There are various reasons why developers might be required to use core javascript, and sometimes a library like jQuery is just overkill. – squidbe Oct 24 '12 at 20:41