Over a million developers have joined DZone.

Unobtrusive JavaScript To Register Code To Be Run Once The Page Is Loaded

·
from http://simon.incutio.com/archive/2004/05/26/addLoadEvent


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

To add an event:

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */ 
});

Tested on IE 5, 5.5 and 6 for Windows; IE 5 and Safari for Mac; Opera 7.5 and FireFox on Mac. Fails on Opera 6.
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}