Add load event

Date published: 7th March 2008

When a web page has finished loading the onload event is triggered. This is attached to the window 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 or Simon Willison's addLoadEvent function.

Anonymous Function

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

addLoadEvent Function

The 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:

The addLoadEvent function takes as an argument another function which should be executed once the page has loaded. Unlike assigning directly to window.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: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.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 using addLoadEvent 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

abunchofletters.co.uk © Rich Wilson 2007–2010 | Valid XHTML 1.0 Strict button Valid CSS button | Future-Proof | hilkat | Hosting by DreamHost