开发者

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


Wrap them.

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜