Using Multiple JavaScript Onload Functions

Unfortunately, you cannot place multiple onload events on a single page. You can nest multiple functions within the one onload call, but what if you need to cascade an onload script across multiple pages, some which may already have an existing onload event? use the addLoadEvent function below.
JavaScript

The function below was written by Simon Willison. It has several advantages. For one, it's really unobtrusive. It can be placed in a file with your other scripts or in a separate file. (If it's in a separate file, just be sure to call it after the other files, so the functions will be available.)

Also, it works even if the onload event handler has been previously assigned. Simon explains it like this:

"The way this works is relatively simple: if window.onload has not already been assigned a function, the function passed to addLoadEvent is simply assigned to window.onload. If window.onload has already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards."

Isn't that beautiful? So, if you already have a script that uses the onload event handler, you don't need to dig it out and change it, unless you want to. It also allows for extra code.

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		} 
	} 
} 

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad); 
addLoadEvent(function() { 
       /* more code to run on page load */ 
}); 

Here's an example that calls two functions and adds a third, independent addLoadEvent:

function func1() { 
  alert("This is the first."); 
}
 
function func2() { 
  alert("This is the second."); 
}
 
function addLoadEvent(func) { 
  var oldonload = window.onload; 
  if (typeof window.onload != 'function') { 
    window.onload = func; 
  } else { 
    window.onload = function() { 
      if (oldonload) { 
        oldonload(); 
      } 
      func(); 
    } 
  } 
}
 
addLoadEvent(func1); 
addLoadEvent(func2); 
addLoadEvent(function() { 
	    document.body.style.backgroundColor = '#EFDF95'; 
}) 

Written by Lee Underwood from www.webreference.com/programming/javascript/onloads/index.html
Code written by Simon Willison at simonwillison.net


Posted by fbrefere001 on Thursday August 25, 2016