Paul Irish

Making the www great

Automate Firing of Onload Events

I’ve often had to set up onload events that execute for only a single page. I’ve both hardcoded those function calls right into the markup and I’ve done page detection in a shared js file (parsing the current URL, ew!). Neither solution is rather pretty. The below solution keeps things unobtrusive.

Set up the body tag with an ID that identifies the page, such as:

1
<body id="homepage">

Over in your javascript, set up your page init code in an object literal:

1
2
3
4
5
6
7
8
9
10
11
12
var siteNameSpace  = {
   homepage : {
      onload : function(){
         // do this stuff.
      }
   },
   contact : {
      onload : function(){
         // onload stuff for contact us page
      }
    }
};

Your document ready code executes for the same for all pages:

jQuery:

1
$(document).ready( siteNameSpace[ document.body.id ].onload );

Prototype:

1
Event.observe(window, 'load', siteNameSpace[ document.body.id ].onload );

YUI:

1
YAHOO.util.Event.onDOMReady( siteNameSpace[ document.body.id ].onload );

However this will fail if that object (and onload function) are not defined. But you can fix it with a little more code..

1
2
3
4
5
6
7
8
9
//jQuery version
$(document).ready(
  function(){
    var NS = window.siteNameSpace, bID = document.body.id;
    if(NS && NS[ bID ] && (typeof NS[ bID ].onload === 'function')){
      NS[ bID ].onload();
    }
  }
);
2009.03.11 I’ve put this technique on steroids, now. Check out Markup-based unobtrusive comprehensive DOM-ready execution

Comments