Add load event

Date Published:
Last updated:

Back

When a web page has finished loading theonload event is triggered. This is attached to thewindow object. You could and should use it to run a function when the page loads:

window.onload = functionName;

This works fine, but what if you want to execute more than one function once the page has loaded? You can only call window.onload once. In fact, if you tried to use it twice, only the latter call would actually execute. Fortunately, there are at least a couple of solutions: an anonymous function orSimon Willison's addLoadEvent function.

Anonymous Function

window.onload = function() {
  function1();
  function2();
  etc();
}

addLoadEvent Function

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

Adding onload calls:

addLoadEvent(function1);
addLoadEvent(function2);
addLoadEvent(etc);

I'll leave the explanation of the code to the author:

TheaddLoadEvent function takes as an argument another function which should be executed once the page has loaded. Unlike assigning directly towindow.onload, the function adds the event in such a way that any previously added onload functions will be executed first.

The way this works is relatively simple: ifwindow.onload has not already been assigned a function, the function passed toaddLoadEvent is simply assigned towindow.onload. Ifwindow.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards.

addLoadEvent has one very important property: it will work even if something has previously been assigned to window.onload without usingaddLoadEvent itself. This makes it ideal for use in scripts that may be executing along side other scripts that have already been registered to execute once the page has loaded.

Further reading and sources