In order to make the function execute only after the page is loaded, we will bind the function to the onload event:
window.onload = userFunction
But what if there are two functions: firstFunction() and secondFunction(), which both want them to be executed after the page is loaded? If so:
window.onload = firstFunciton;window.onload = secondFunction;
Only the last function can be executed. From this we can see that each event handler can only bind one instruction.
But we can do this:
window.onload = function(){ firstFunction(); secondFunction(); }This is a solution.
However, there is a more convenient solution - writing some extra code, but the advantage is that with this code, binding the functions, no matter how many they are, is very concise and easy to do.
The name of this function is addLoadEvent, which is written by Simon Willison. It has only one parameter: the name of the function to be executed when the page is loaded.
Here is the operation that the addLoadEvent() function will complete:
1. Store the value of the existing window.onload event handler function into the variable oldonload.
2. If no function is bound to this processing function, add the shape function to it as usual.
3. If some functions are already bound to this processing function, append the shape function to the end of the existing instruction.
Here is a list of codes for the addLoadEvent() function:
function addLoadEvent(func){ var oldonload = window.onload; if(typeof window.onload != 'function'){ window.onload = func; }else{ window.onload = function(){ oldonload(); func(); } }}This is equivalent to creating a queue for functions that will be executed when the page is loaded. If you want to add the two functions just now to the queue, you just need to write the following code:
addLoadEvent(firstFunction); addLoadEvent(secondFunction);
The above method of binding multiple JavaScript functions to the onload event handling function is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.