Archive

Archive for January, 2008

Automate firing of onload events

January 14th, 2008

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:

<body id="homepage">

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

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:

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

Prototype:

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

YUI:

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..

//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

javascript

Javascript CSS Selector Engine Timeline

January 13th, 2008

I'm interested in understanding all the selector engine code. In order to watch the development from the most basic to the quickest, I wanted to gather all the data points. Take a look, as you can see, Jack Slocum was definitely right when he said "selector processing power has gone from Pinto power to a Mustang GT 500."

Update: Added Base2, CssQuery1.0. Corrected jQuery launch date.
Update: Added Dojo 0.9, NWMatcher.

Leave a comment if I left anything out.

2012.04.25 (four years later): I've referenced this timeline in my StackOverflow answer to What is the source of the double-dollar sign selector query function in chrome / firefox?. :)

javascript