The event is triggered when the page has finished loading onload
. Based on the idea that content (HTML) is separated from behavior (JavaScript), we need to write some initialization of the page in the method and window.onload = functionName
call these methods.
When multiple methods need to be called, window.onload = functionA; window.onload = functionB;
only the last method is actually called if used. So how do you implement calling multiple methods?
Write directly in HTML:
<onload= "Functiona (); Functionb ()">
This method is not recommended because the event is contained within the HTML and does not conform to the "content and behavior separation" concept described above.
Create an anonymous function that holds the method that needs to be called, and then bind the anonymous function to the onload
event:
function () { Functiona (); Functionb ();}
This is the simplest solution when there are not too many functions that need to be called.
When there are many methods to invoke, we can further refine and write a method specifically for binding onload
events:
functionAddloadevent (func) {//depositing the value of an existing Window.onload event handler function into a variable varOldonload =window.onload; if(typeofWindow.onload! = "function") { //if the handler has not yet bound any functions, add new functions as usualWindow.onload =func; } Else { //if the handler has already bound some functions, add the new function to the endWindow.onload =function() {oldonload (); Func (); } } } //Next, we just need to call this method to add the function we need .addloadevent (Functiona); Addloadevent (FUNCTIONB);
Now, no matter how complicated the code becomes, when we need to call the number of functions when the page is loaded, we just need to write a single statement to resolve it.
Reference:
- JavaScript DOM Programming Art (second edition)
- Simon Willison ' s blog
How the onload event in JavaScript binds multiple methods