1Window. onload = myfunction ();
Suppose we want a function to be executed immediately after the webpage is loaded. AOnloadEvent, so we can useOnloadEvent to load this function.OnloadEvents andWindowObject Association. For example:
SetMyfunctionThe function is bound to this event:
A function can be used to solve this problem.,What about two, three, or more? How can this problem be solved ??
Suppose we haveFirstfunctionAndSecondfunctionAre the two functions written as follows:
1Window. onload =Firstfunction;2Window. onload = secondfunction;
However, each processing function can only bind one instruction. So none of the above. BecauseSecondfunctionFunction will replaceFirstfunctionFunction.
There is a way to help us solve the above problem: we first create an anonymous function to accommodate the two functions, and then bind the anonymous functionOnloadThe event is as follows:
1Window. onload =Function(){2 Firstfunction ();3 Secondfunction ();4}
This is indeed a good and simple answer.
But there is still an optimal solution-no matter how many functions you want to execute after page loading, you can easily implement this function.
This function is namedAddloadevent. This function has only one parameter: this parameter specifies the name of the function to be executed after the page is loaded.
Addloadevent ()FunctionCodeAs follows:
1 Function Addloadevent (func ){ 2 VaR Oldonload = Window. onload; 3 If ( Typeof Window. onload! = 'Function' ){ 4 Window. onload =Func; 5 } 6 Else { 7 Window. onload = Function (){ 8 Oldonload (); 9 Func (); 10 } 11 } 12 }
AddloadeventThe function mainly performs the following operations:
1, Put the existingWindow. onloadThe value of the event processing function is savedOldonload.
2If no function is bound to the handler, add the function to it.
3. If some functions have been bound to this handler function, append the function to the end of the existing one.
PassAddloadeventFunction. You only need to call this function to bind it.
1 Addloadevent (firestfunction );2Addloadevent (secondfunction );
So this function is very useful, especially when the Code becomes very complex. No matter how many functions you want to execute when the page is loaded, you only need to write a few more statements. Convenient and practical.