Article Introduction: no matter how many functions you plan to perform when the page is loaded, he can handle it. This scenario requires some extra code, but the advantage is that once you have the code, it's very easy to bind the function to the Window.onload event. |
Suppose two functions: Firstfunction and Secondfunction. What if you want both functions to be executed while the page is loading? If they are gradually bound to the OnLoad event, only the last one of them will be actually executed:
Window.onload = firstfunction;
Window.onload = secondfunction;
Secondfunction will replace Firstfunction. You might think: Each event handler can only bind one instruction.
One way to avoid this dilemma is to create an anonymous function to accommodate the two functions, and then bind that anonymous function to the OnLoad event as follows:
Window.onload = function () {
firstfunction ();
Secondfunction ();
}
He does work well-it should be the simplest solution when there are not many functions to bind.
There is also an optimal solution--no matter how many functions you plan to perform when the page is loaded, he can handle it well. This scenario requires some extra code, but the advantage is that once you have the code, it's very easy to bind the function to the Window.onload event.
Here's what the Addloadevent function will do.
- The value of the existing Window.onload event handler is stored in the variable oldonload.
- If you have not yet bound any function on this handler, add the new function to it as usual.
- If some functions are already bound on this handler, the new function is appended to the end of the existing instruction.
function Addloadevent (func) {
var oldonload = window.onload;
if (typeof window.onload!= ' function ') {
window.onload = func;
} else {
window.onload = function () {
old OnLoad ();
Func ();}}
This creates a queue of functions that are executed when the page is loaded. If you want to add just the two functions to the queue, you just need to write the following code:
Addloadevent (firstfunction);
Addloadevent (secondfunction);
This function is very practical, especially when the amount of code becomes more and more complex. No matter how many functions you intend to perform when the page is loaded, you can arrange everything by writing one more statement.