Stop The Window.Onload Madness
There are a lot
cool
javascript
libraries
floating around the Intarweb these days that add cool behavior to web
pages. My favorites are the ones that you simply add to the head
section of your website and control via
markup.
It is a great way to enhance structural html markup with
Javascript.
Unfortunately many of these attempt to hijack the window.onload
event.
Ok, a show of hands (and I have been guilty of this as well). How many
of you have written code like this to handle the onload event in
javascript within a .js file?
function init()
{
}
window.onload = init;
Stop it!
That line of code will completely wipe out any other functions that were attached and ready to handle the onload event. How arrogant of your script to do so. Instead, your script should learn to play nicely.
Unfortunately, Javascript doesn’t support the delegate syntax that C# has. It’d be nice to be able to do this.
function init()
{
}
window.onload += init;
But that won’t work. One approach I found on Simon Incutio’s blog (which is used by the original LightboxJS script) involves using a method that safely attaches an event handling method to the onload event without overwriting existing event handlers.
It works by checking to see if there any methods are already attached to the event. If so it attaches a new anonymous method that calls the original method along with the method you are attempting to attach.
Here is a snippet demonstrating this technique.
function highlightXFNLinks()
{
// Does stuff...
}
//
// Adds event to window.onload without overwriting currently
// assigned onload functions.
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
}
else
{
window.onload = function()
{
oldonload();
func();
}
}
}
addLoadEvent(highlightXFNLinks);
This is pretty nifty, but there appears to be a whole new school of
script libraries that provide this sort of functionality for attaching
to any event, not just the window.onload
event.
I am sure you Javascript Gurus will expose how out of date and ignorant I am of this area (it is true) but the few that I have heard of that seem to be catching on like wildfire are the Prototype JavaScript Framework (often just referred to as prototype.js), the Dojo Toolkit, and Behaviour.
I will probably end up rewriting all my libraries to use one of these
tooltips so that I stop duplicating code. Since each of my javascript
libraries are stand-alone, I make sure to include the addLoadEvent
method in each of them. But I think its time to allow a dependency on
another script to avoid this duplication.
Comments
15 responses