Return to Snippet

Revision: 13171
at April 13, 2009 11:20 by juzerali


Initial Code
Here is a basic tutorial on how to have multiple onload functions.

First we need an array to store the functions we wish to have executed onload. We will call it myonload.
Javascript Code:
var myonload = [];

To add a function to onload, in this case, a function called my_function, and another called another_function, we simply do
Javascript Code:
// These functions must have been defined before you add them to the array
myonload.push(my_function);
myonload.push(another_function);

push() adds an element to the end of an array (and returns the new length of the array.) You could also do myonload[myonload.length] = my_function; if you please, but I prefer the push() method. push() at w3schools

Now we have an array of functions we want to execute onload. I will explain how to add the onload handler later, but here is our function to run these functions.
Javascript Code:
function doonload()
{
	var len; // initialize variable
	if( (len = myonload.length) ) // if we added any functions to our array
	{
		for( var i=0; i<len; i++ ) // iterate over each item in the array
		{
			myonload[i]();
			/*
			 * () after the current item to execute the function.
			 * Without () after the variable it would do nothing.
			 */
		}
	}
}

Now that we have our array of onload functions, and a function to execute them, we need to tell the browser to run them when it finishes loading. One way, is to call our doonload function with the onload attribute of the <body> tag.
HTML Code:
<body onload="doonload();">

That is not our best option of course. A better way of doing this is with a little tidbit of Javascript that adds doonload as the handler for the onload event. This has to be done AFTER the function declaration of doonload.
Javascript Code:
if( window.addEventListener ) // if the browser supports addEventListener
{
	window.addEventListener("load", doonload, false);
}
else if( window.attachEvent ) // otherwise, if it suuports attachEvent
{
	window.attachEvent("onload", doonload);
}

All of it put together:
Javascript Code:
var myonload = [];

myonload.push(my_function);
myonload.push(another_function);

function doonload()
{
	var len;
	if( (len = myonload.length) )
	{
		for( var i=0; i<len; i++ )
		{
			myonload[i]();
		}
	}
}

if( window.addEventListener )
{
	window.addEventListener("load", doonload, false);
}
else if( window.attachEvent )
{
	window.attachEvent("onload", doonload);
}

Initial URL
http://www.tutorialized.com/view/tutorial/Multiple-onload-functions/36969

Initial Description
by tutorialized.com

Initial Title
how to run multiple onload functions through JavaScript

Initial Tags
javascript

Initial Language
JavaScript