Chain JavaScript Events

In JavaScript there can be only one JavaScript onload event handler. This is a somewhat an issue if you have all sort of third party libraries that want to run some piece of JavaScript code when the page finishes loading. You can use the YUI! Event library add and chain event listeners to a DOM element, but adding another resource dependency to you application might not always be the right answer. I recently had to chain some onload event handlers for a simple script I was writing and I didn’t want to require any additional files. Here is my poor man’s version of a JavaScript event chain gang.

// The loaders array will contain a
// list of event handlers
if(!window.loaders) {
  window.loaders = new Array(0);
}
// Save the current event handler
if(window.onload) {
  window.loaders.push(window.onload);
}
// Attach new onload event handler
window.onload = function() {
  // Execute previous cached event handlers.
  for(var i=0; i < window.loaders.length; i++) {
    var func = window.loaders[i];
    func();
  }

  // New event handler code goes here...
}

With code like this you can guarantee that the old even handler code will run before your new code.

Related posts:

  1. The Anatomy of a JavaScript Bookmarklet
  2. Unobtrusive JavaScript with Prototype and Behavior
  3. Put JavaScript To Sleep
  4. Dynamically Create HTML Elements with JavaScript
  5. JavaScript FX

This entry was posted in JavaScript, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Posted June 20, 2007 at 4:09 pm | Permalink

    Simon Willison’s addLoadEvent which uses closures is well worth a look: http://simonwillison.net/2004/May/26/addLoadEvent/

  2. Posted June 21, 2007 at 1:14 am | Permalink

    @Ed – Thanks for the tip. That was helpful. The above code is, in my mind, the simplest possible way to chain events. The next step would be to pass functions as parameters, much like Simon’s describes. But perhaps the best option is just to use some commonly maintained library. Once again, thanks!

  3. Posted June 21, 2007 at 7:25 pm | Permalink

    Am I missing something here? Would addEventListener/attachEvent not work here?

  4. Posted June 23, 2007 at 9:53 am | Permalink

    @Alex – I think I am just being stubborn, :). I wanted to stay away from having to check if the browser supports either addEventListener, attachEvent, or neither. So I thought the simplest hack that would work would be something like the above. I agree with you though, for ‘production’ type of work I would use some supported JavaScript library that abstract the use of addEventListener/attachEvent.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*