[Javascript] combining multiple window.onloads

Paul Novitski paul at novitskisoftware.com
Thu May 5 01:27:27 CDT 2005


Many of us are using window.onload in external scripts to execute a 
function when the page finishes loading.  Instead of:

	<body onload="fn1();">

in the HTML, we use:

	window.onload = fn1;

in an external script.

A common problem is how to handle more than one external script.  This is 
easy using inline scripting:

	<body onload="fn1(); fn2();">

but not so simple using pure javascript.  It doesn't work to stack 
window.onload statements like this:

	window.onload = fn1;
	window.onload = fn2;

because the second statement simply replaces the first.

One common method is to create a kind of central switchboard:

	window.onload = function()
	{
		fn1();
		fn2();
	}

however this (like the body onload method) needs to be edited each time a 
function is added or removed from the application.

Much better to use logic that automatically concatenates onload functions.

Googling around I've found a few different techniques for doing this.  My 
favorite (for its simplicity) was explicated by Toby Mills in the Evolt 
listserve in early 2004 
<http://lists.evolt.org/archive/Week-of-Mon-20040216/155696.html>.  Here it 
is, expanded for readability:
_________________________

var oldLoad = window.onload;

window.onload = function()
{
		if (oldLoad)
		{
			oldLoad();
		}
	fn1();
}
_________________________

This logic replaces the simple window.onload statement in each script.

Here are two other, less simple methods:

building an array of functions:
http://www.webmasterworld.com/forum91/3647.htm

using addEventListener():
http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html

Comments?

Paul





More information about the Javascript mailing list