views:

217

answers:

3

Hi there,

I know calls to $(function(){ }) in jQuery are executed in the order that they are defined, but I'm wondering if you can control the order of the queue?

For example, is it possible to call "Hello World 2" before "Hello World 1":

$(function(){ alert('Hello World 1') });
$(function(){ alert('Hello World 2') });

The question is whether or not it's possible... I already know it goes against best practice ;)

+1  A: 

Those functions are added to a private array readyList, so I'd say it isn't accessible for manipulation.

http://github.com/jquery/jquery/blob/master/src/core.js#L47

patrick dw
+1  A: 

It can be done, but not easily. You'd have to hack jQuery itself, probably here. Before jQuery starts calling these functions inside the while loop, you'd have to add code to inspect the readyList array and re-order the elements according to your preference.

Ken Redler
+4  A: 

here is how you would go about doing it:

// lower priority value means function should be called first
var method_queue = new Array();

method_queue.push({
  method : function()
  { 
    alert('Hello World 1');
  },
  priority : 2
});

method_queue.push({
  method : function()
  { 
    alert('Hello World 2');
  },
  priority : 1
});


function sort_queue(a, b)
{
  if( a.priority < b.priority ) return -1;
  else if( a.priority == b.priority ) return 0;
  else return 1;  
}

function execute_queue()
{
  method_queue.sort( sort_queue );

  for( var i in method_queue ) method_queue[i].call( null );
}

// now all you have to do is 
execute_queue();

You can read more about it here

ovais.tariq