开发者

Controlling sequence of jQuery load function

开发者 https://www.devze.com 2023-01-04 19:48 出处:网络
I have just started to use jQuery from prototype and am working with the load function to execute some scripts once the page has been loaded开发者_如何学Python:

I have just started to use jQuery from prototype and am working with the load function to execute some scripts once the page has been loaded开发者_如何学Python:

$(window).load(
function()
{
Stuff happens
}
);

However, how do you add a list of functions and control the order in which they execute? It's difficult to put everything I want to load in the 'stuff happens' area, so i need to be able to add and remove stuff from an array and change the order. Then one page load, execute that list.

Any clues?


You might try something like this.

First, set up your functions:

var func1 = function(){ alert('this'); };
var func2 = function(){ alert('that'); };

Next, make an array to contain them in the desired order:

var funcs = [
  function(){alert('a');}, // anonymous, defined inline
  function(){alert('b');}, 
  func2,                   // or by reference
  func1,                   // you control the sequence
];
funcs.push( function(){alert('c');} ); // etc

Finally, in your load handler:

$(window).load( function(){
  $.each( funcs, function(i,thisfunc){ // or native js for() if you prefer
    thisfunc();
  });​
});

When the load event triggers, you'll get the alerts a b that this c. This isn't all that different from how jQuery handles this sort of thing with its private readylist array.

0

精彩评论

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

关注公众号