How to set more window.onload events?

I have three functions that I would like to call when the page is loaded. I tried this:

window.onload = [function f1(){...}, function f2(){...}, function f3(){...}]; 

Unfortunately this will not work. I do not know how to do this.

+4
source share
5 answers

You cannot install multiple event handlers; they are not supported. If you need to perform several functions, you just need to call them sequentially one after another:

 function f1() { ... } function f2() { ... } function f3() { ... } window.onload = function() { f1(); f2(); f3(); } 

Most javascript libraries provide you with ways to add a few function calls to the event handler - and will chain you. For example, using jQuery you can do this:

 $(window).load(function() { ... }); $(window).load(function() { ... }); $(window).load(function() { ... }); 

This will not cancel the previous call with the new one, but will trigger all three calls from the onload .

UPDATE: another way to deal with it is to use addEventListener for 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 pieces of code are equivalent to the first - and to each other.

+3
source

In the category of code obfuscation, here you can consider as a brain exercise:

 window.onload = function() { return this.forEach(Function.prototype.call, Function.prototype.call); }.bind([function f1(){...}, function f2(){...}, function f3(){...}]); 

It will work in browsers that implement Array.forEach() and Function.prototype.bind() .

+1
source

Just wrap all functions in an anonymous function

 window.onload = function(){ f1(); f2(); f3(); } 
0
source

You can define your functions before calling them from a single function:

 window.onload = function () { f1(); f2(); f3(); } 

With addEventListener() you can define more than one listener for onload . Listeners are executed in order of definition.

0
source

Use the function to dynamically add:

 function addWindowOnload(next) { var prev = window.onload; window.onload = function() { if (prev) prev(); next(); }; } 
0
source

Source: https://habr.com/ru/post/1501429/


All Articles