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.