1

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?

3 Answers 3

3

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

Advanced event registration models

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.