Javascript Window.Onload Function Chaining
-
21-08-2019 - |
Question
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?
Solution
May be it will be better to use addEventListener/attachEvent?
OTHER TIPS
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.
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/