Js window.onload loads multiple functions and appends functions

  • 2020-03-30 01:14:50
  • OfStack

Window.onload is often used for projects,

The usage is as follows:

Function func(){alert("this is window onload event!") ); The return; }

Window. The onload = func;

Or:

Window.onload =function(){alert("this is window onload event!" ); The return; }

But window.onload cannot load multiple functions at once.

Such as:

The function of t () {
Alert (" t ")
}
The function b () {
Alert (" b ")
}
Window. The onload = t;
Window. The onload = b;

I'm going to overwrite the previous one, and the above code is only going to print b.

At this point, the following solution can be used:
Window. The onload = function () {t ();   (b); }

Another solution is as follows:


 function addLoadEvent(func) {
  var oldonload = window.onload;//I get the function of the last onload event
  if (typeof window.onload != 'function') {//To determine if the type is 'function', notice that typeof returns a string
    window.onload = func;
  } else {  
    window.onload = function() {
      oldonload();//Call the function that overrides the onload event --> Since I don't know much about js, I temporarily understand it as a function that overrides the onload event to load multiple functions
      func();//Call the current event function
    }
  }
}
//The full example is used as follows:
function t(){
alert("t")
}
function b(){
alert("b")
}
function c(){
alert("c")
}
 function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {  
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
addLoadEvent(t);
addLoadEvent(b);
addLoadEvent(c);
//Equivalent to   Window. The onload = function () {t ();   (b); (c); }

Window. onload =function() {t();   (b); (c); }) faster, of course, use addLoadEvent more professional, all right!

JS window.onload append function:


<script>
if(window.attachEvent)//IE: If it exists in the browser window.attachEvent The function USES window.attachEvent function , Judge whether IE You can also use :if (document.all){//..}
window.attachEvent("onload",function() {alert("add method");});
else  //FireFox
window.addEventListener("load",function() {alert("add method");},true);
</script>

Run, alert in js pops up message, problem solved.

================ ====

AttachEvent    Binds the specified function to an event so that it is called whenever the event fires on the object.


Related articles: