I have three functions, which I would like to call, when the page is loaded. I tried this:
window.onload = [function f1(){...}, function f2(){...}, function f3(){...}];
Unfortunately this doesn't work. I have no idea how should I manage it.
I have three functions, which I would like to call, when the page is loaded. I tried this:
window.onload = [function f1(){...}, function f2(){...}, function f3(){...}];
Unfortunately this doesn't work. I have no idea how should I manage it.
You can't set multiple event handlers, it's not supported. If you need to execute multiple functions, then you just have to call them sequentially one after another:
function f1() { ... }
function f2() { ... }
function f3() { ... }
window.onload = function() {
f1();
f2();
f3();
}
Most of javascript libraries provide you with ways to add multiple function calls to the event handler - and will do the chaining for you. For example, with jQuery you can do this:
$(window).load(function() { ... });
$(window).load(function() { ... });
$(window).load(function() { ... });
This will not override the previous invocation with the new one, but will set all three to be called from the onload
event.
UPDATE: another way of dealing with it would be to use addEventListener
on your window
object.
function f1() { ... }
function f2() { ... }
function f3() { ... }
window.addEventListener("load", f1);
window.addEventListener("load", f2);
window.addEventListener("load", f3);
or even
window.addEventListener("load", function() { ... });
window.addEventListener("load", function() { ... });
window.addEventListener("load", function() { ... });
These two code snippets are equivalent to the first one - and with each other.
Under the category of obfuscated code, here's an option to consider as brain exercise:
window.onload = function() {
return this.forEach(Function.prototype.call, Function.prototype.call);
}.bind([function f1(){...}, function f2(){...}, function f3(){...}]);
It will work on browsers that implement Array.forEach()
and Function.prototype.bind()
.
Just wrap all the functions in a anonymous function
window.onload = function(){
f1();
f2();
f3();
}
You can define your functions before calling them from one function:
window.onload = function () {
f1();
f2();
f3();
}
With addEventListener()
you can define more than one listener for onload
. Listeners are executed in the order of definition.
Use a function to add them dynamically:
function addWindowOnload(next) {
var prev = window.onload;
window.onload = function() {
if (prev) prev();
next();
};
}