Aditya Singh
Aditya Singh

Reputation: 9612

Javascript function call

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...

Upvotes: 1

Views: 410

Answers (4)

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

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.

Upvotes: 1

deveffort
deveffort

Reputation: 33

Why not have an old school way of having as many function calls inside one function invoked on page load? window.addEventListener("load", Foo, false);

where Foo has calls to all required functions. This way you can control the order and return values if required.

Upvotes: 0

nnevala
nnevala

Reputation: 5997

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.

Upvotes: 4

tdammers
tdammers

Reputation: 20706

Wrap them.

window.onload = function() { MyFunc(); MyOtherFunc(); }

Upvotes: 11

Related Questions