9

recently I came up with the following problem:

In my web site in all html pages I call a function in body onLoad event:

<body onLoad="func1();">

This is part of my template for html, so it appears on every page in my site and I can't change that. Now, the deal is that on some pages, I need to call some other functions onload and I tried with window.onload property, but it wipes the calling of func1...

I now that I can just say:

window.onload = func2(); //where func2() calls to func1()

but this seems dirty and lame? Isn't it ?

So, is there a way to add some functions to those that are about to be executed onload, without deleting the old one? In addition I use asp.net if that could help ...

Thanks!

3
  • What I see in the answers is that jquery is likely the best we can get. Or we can go for some dirty tricks and hacks.
    – anthares
    Feb 16, 2010 at 23:41
  • 2
    I don't think the "anonymous functions" method is "a dirty trick or hack". It's quite neat actually... and uses one of the most powerful features of JavaScript. Feb 16, 2010 at 23:53
  • I agree, it's a good alternative, too.
    – anthares
    Feb 16, 2010 at 23:57

5 Answers 5

19

You can use jQuery to chain on load handlers. Repeatedly using jQuery.load or jQuery(document).ready will chain your handlers (I believe). You other option is to do it programmatically, which means you need an auxiliary function that will chain your onload handlers for you. You can do this with a closure (or anonymous function):

var addOnLoadHandler = function(newHandler) {

    if (typeof window.onload != 'function') {
        window.onload = newHandler;
    }

    else {
        var oldHandler = window.onload;
        window.onload = function() {
            if (oldHandler) {
                oldHandler();
            }
            newHandler();
        };
    }
};

You will have to bind your functions programmatically though, so you would have to do:

addOnLoadHandlers(function() {
 alert("Hi I am the first onLoad handler!");
});

addOnLoadHandlers(function() {
 alert("Hi I am the second onLoad handler!");
});

in a javascript file (or in your html file).

Another approach is to use an array:

var onloaders = new Array();

function runOnLoads() {
    for (i = 0; i < onloaders.length; i++) {
        try {
            var handler = onloaders[i];
            handler();
        } catch(error) {
            alert(error.message);
        }
    }
}

function addLoader(obj) {
    onloaders[onloaders.length] = obj;
}

In your HTML or Javascript file you do:

addLoader(function() {
 alert("Hi I am the first onLoad handler!");
});

addLoader(function() {
 alert("Hi I am the second onLoad handler!");
});

Then in your html you can just do <body onload="runOnLoads()">

5

You may want to make the best out of anonymous functions:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

Borrowed from the Top 10 custom JavaScript functions of all time.

5

jQuery has a nice shorthand for adding multiple defined handlers to the "ready" event (does not work with anonymous functions where you have to use $(document).ready(function(){});).

simply

$(myFunction);
$(myFunction2);

One big advantage is that if the DOM has already loaded, this still gets fired, whereas anything you bind to window.onload after the event will not get called.

3

have you considered a javascript library like jquery, i know that there are other approaches but jquery will make your life so much easier...

$(function(){
   //Do stuff when DOM is loaded.
   func1();
    $('#link').click(function(){
        //bind a click event
    });
});

The classic approach is to just stick all of your functions at the bottom of the page :)

6
  • OK, but some of the functions I want to be called on every page and some only on some specific pages. And when I say "on every" page, I want to write it on a single place. How jquery is going to help me ?
    – anthares
    Feb 16, 2010 at 22:48
  • What if he doesn't want to use jQuery? @anthares, if you want some functions to be called only on specific pages, you need javascript on those pages that will add the specific onload handlers you need. Feb 16, 2010 at 22:51
  • @anthares, well since you say asp.net, are you using a masterpage? if so but the general ones in there, if not then i guess you need to wrap a function aroung the common ones and call it in everypage. JQuery just makes everything easier and terser. Feb 16, 2010 at 22:53
  • 2
    @Paul hehe there may be more elegant approaches :) Feb 16, 2010 at 22:55
  • @vivin, indeed but i don't consider iterating through an array of delegates elegant when there are solutions like jquery around. Feb 16, 2010 at 22:58
3

In jquery you can do

$(document).onload(function() {
  // do something
}

//then later on do

$(document).onload(function() {
  // do something here too!
}

jQuery will intelligently add both events to the onload event and both will be executed when the page loads. With jQuery you also get crossbrowser support as an added bonus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.