Conditional onLoad Queue

Dec 04, 2006 22:14

I was writing some JavaScript recently and I came across a situation where I needed to perform different functions with the body element's onLoad event handler depending on varying circumstances. It may sometimes be necessary to queue onLoad events from scripts embedded in a document's head element. However, at that point during the creation of a document, the body element doesn't exist yet!

Here's an example of what I mean:

Document Title Goes Here

onload="functionNameThatMayChangeHere();">

Document Content Goes Here

Right now, this example document would always call functionNameThatMayChangeHere() once the body is finished loading. What if, inside of the external script, I needed to load different functions depending on certain conditions? I've created a way to do just that. Save the following code as onLoad.js:

var onLoadActions = new Array();

function addOnLoadAction(action)
{
onLoadActions[onLoadActions.length] = action;
}

function performOnLoadActions()
{
for (i in onLoadActions)
{
eval(onLoadActions[i]);
}
}

Then, include onLoad.js in your document's head before any other scripts, and call performOnLoadActions() from the body's onLoad event handler:

Document Title Goes Here

Document Content Goes Here

With these modifications, all you have to do in order to schedule an action for performing on body load is use the following syntax within your own script:

addOnLoadAction("alert('Hello, world!');");
addOnLoadAction("functionNameThatMayChangeHere();"); // Look familiar???
addOnLoadAction("window.location = 'http://www.fsf.org/';");
Previous post Next post
Up