views:

752

answers:

3

Just for the sake of experimentation, I've been trying to determine different ways to non-destructively chain window.onload functions in a web browser. This is the idea of what I have so far:

var load = window.onload;
var newFunction = function(){
    alert("ha!");
}
window.onload = function(){
    load();
    newFunction();
}

The problem I see with this is that every time you chain a function, it adds another level of function calls to the stack. Is there a better way to go about this that doesn't add unnecessary depth to the call stack?

A: 

You could have a look at jQuery how they handle that.

From the jQuery docs:

You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.

Endlessdeath
+2  A: 

May be it will be better to use addEventListener/attachEvent?

Advanced event registration models

maxnk
A: 

I'd rather use the "good enough" addEvent:

var addEvent = function( obj, type, fn ) {
        if (obj.addEventListener)
                obj.addEventListener(type, fn, false);
        else if (obj.attachEvent) 
                obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));});
}

From: http://www.ilfilosofo.com/blog/2008/04/14/addevent-preserving-this/

Kit Sunde