How to call more than one javascript function on the window's onload event?
For Ex,
window.onload=MyFunc(); //Single Function
But what if there are more than one functions to call on the window's onload event...
Or you could bind the functions to the window's load event:
window.addEventListener("load", MyFunction, false);
window.addEventListener("load", MyOtherFunction, false);
For IE legacy you might need to use the attachEvent method:
window.attachEvent("load", MyFunction);
window.attachEvent("load", MyOtherFunction);
Problem with this approach is that the order in which the functions are executed can not be counted on.
attachEvent code on IE<9.Here is a sample piece that would explain HOW:
// create an array that will contain all
// your functions that you would like to
// call on page load
var pageOnLoadEvents = [];
// Add one or more functions in pageOnLoadEvents array
pageOnLoadEvents.push(function() { alert("Hello!"); })
pageOnLoadEvents.push(function() { alert("How are you?"); })
// This will call when your page will load
window.onload = function() {
// Loop through each index of pageOnLoadEvents
for(var index = 0; index < pageOnLoadEvents.length; index++) {
// '()' brackets in the end tell them to make a call
// If you don't include '()' at the end this will
// suspect as a object as in JavaScript functions
// are first-class objects.
// document.write(pageOnLoadEvents[index].toString()); // treat as object
pageOnLoadEvents[index]();
}
}
The above sample tried to be made simple to give you explanation on your question. However, there is a good explanation on Simon Willison’s Weblog, he wrote:
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 */
});
The addLoadEvent function takes as an argument another function which should be executed once the page has loaded. Unlike assigning directly to window.onload, the function adds the event in such a way that any previously added onload functions will be executed first. Read more.
MyFuncreturns a function object. Putting the parentheses afterMyFuncmeans that you call it immediately and the value returned byMyFuncwill be assigned towindow.onload. I imagine you meantwindow.onload=MyFunc.