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:
4 Comments
Simon Willison’s addLoadEvent which uses closures is well worth a look: http://simonwillison.net/2004/May/26/addLoadEvent/
@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!
Am I missing something here? Would addEventListener/attachEvent not work here?
@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.