Calling Multiple Windows Onload Functions In Javascript
March 7th, 2009 by NikhilHeres another little peice of Javascript trickery that I had to dig around because the situation commaned it. In one of my web sites, I had this situation where I had to implement “windows.onload” twice. The first thing that would came to an inexperienced mind like mine ( I have to honestly say that, since I have been using javascript Frameworks and libraries, I have forgotton to do simple things on my own… sad but true), is the following method…
{code type=”javascript”}
window.onload=onloadfn1;
window.onload=onloadfn2;
window.onload=onloadfn3;
etc…
{/code}
Sorry to say but, this wont work… dont want to discuss the execution science of Javascript much … but according to my recent experience, only the last function (onloadfn3) will ill actually get executed.
In normal situations, unlike mine (which I’ll talk about a little later)… you could do one of the following to execute mutliple onload functions ….
OR something like this
{code type=”javascript”}
function doOnLoad() {
onloadfn1();
onloadfn2();
onloadfn3();
}
window.onload = doOnLoad;
{/code}
For my current situation , I cannot use either of the above…
Why did I need to call windows.onload twice, rather that calling two functions within a single onload function? Here is quick look at my problem statement…
“My Site pages are structured like the WORDPRESS theme…. i.e. there is a common Header.php and Footer.php that gets included into all the site pages. There is an onload function implementaion in the Footer.php to do some common onload functions. AND there are few pages that need to something of their own ONLOAD , apart from those done by the common onload function. If I assign callback function directly to the window.onload handler, it will over-ride previously assigned callbacks in the Footer.php”
…. Is my problem understood 🙂 ?
Well! there are few solutions that I did find. They all are very similar and mainly implementions of a solution given by Simon Willison (http://simonwillison.net/2004/May/26/addLoadEvent/)…
Solution :
Simply add this javascript code to site …
{code type=css}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != ‘function’) {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
{/code}And call it instead of the usual “windows.onload”
{code type=css}
addLoadEvent(FunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
}); {/code}
Advantages of this code snippet …
1. Primarily, It lets you have multiple windows.onload events, called from seperate parts of your code, without overridding the previous definition
2. It is really unobtrusive. It can be placed in a file with your other scripts or in a separate file.
3. It works even if window.onload has already been set.
Tags: Tips & Tricks
Subscribe to ExpressingIT by Email | Follow Me on Twitter