What is the difference between window.onload = init(); and window.onload = init;

window.onload = init();

assigns the onload event to whatever is returned from the init function when it’s executed. init will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned to window.onload. It’s unlikely you’d ever want this, but the following would be valid:

function init() {
   var world = "World!";
   return function () {
      alert("Hello " + world);
   };
}

window.onload = init();

window.onload = init;

assigns the onload event to the function init. When the onload event fires, the init function will be run.

function init() {
   var world = "World!";
   alert("Hello " + world);
}

window.onload = init;

Leave a Comment