Never been to DZone Snippets before?

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

About this user

brad

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Unobtrusively Executing JavaScript on Page Load

http://simonwillison.net/2004/May/26/addLoadEvent/

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.

   1  
   2  function addLoadEvent(func) {
   3    var oldonload = window.onload;
   4    if (typeof window.onload != 'function') {
   5      window.onload = func;
   6    }
   7    else {
   8      window.onload = function() {
   9        if (oldonload) {
  10          oldonload();
  11        }
  12        func();
  13      }
  14    }
  15  }
  16  
  17  addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
  18  addLoadEvent(function() {
  19    /* more code to run on page load */ 
  20  });
  21  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS