DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

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

04.07.2005
| 13165 views |
  • submit to reddit
        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.