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;


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(){
function b(){
function c(){
 function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {  
    window.onload = function() {
//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:

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);

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: