tags:

views:

55

answers:

3

Suppose, I have a js file which looks like this:

$(document).ready(function() { // first task} );
$(document).ready(function() { // second task } );
$(document).ready(function() { // third task } );

Upon loading the file the tasks get executed in order. I am not able to understand why ? I'm guessing that the callback methods are fired when an "on ready" event occurs. How is the execution order being retained ? Are the consecutive call backs being queued up in some place ?

Note: I know that this is a very naive way of coding. I have written the snippet only to get my point across and do not write such code in my projects.

+1  A: 

Your handlers are being pushed into an array (readyList) for executing in order later, when the document is ready.

They're queued like this:

readyList.push( fn );

And executed when ready like this:

var fn, i = 0;
while ( (fn = readyList[ i++ ]) ) {
  fn.call( document, jQuery );
}

If the document is already ready, then they'll execute immediately, which is still in order.

Nick Craver
@Nick: in 1.4.3 you can control the order of execution, no?
jAndy
@jAndy - You can't, though you can *delay* the execution of all `ready` handlers, basically saying "hey wait I'm creating more elements!".
Nick Craver
@Nick: Ah interesting. Even if I can't imagine a usecase ad hoc.
jAndy
@jAndy - You can see the commit here: http://github.com/jquery/jquery/commit/747ba7defd82bffa6c7ccb69e53b834cbfddb62c It was originally added to allow async script loading and such to finish, ticket's here: http://bugs.jquery.com/ticket/6781
Nick Craver
jAndy
@jAndy - The issue is it may have *already* fired before your script loaded, so you'd be allowed to delay that `ready` execution...I agree I'll probably never use it, *could* come in handy though.
Nick Craver
Thanks, Nick. The source code references are very useful.
Amrit
+1  A: 

The functions which you specify are in order added to a list. When the DOM is ready, jQuery iterates through that list and invokes the functions in that order.

Your list becomes something like..

handlers = [ function(){ alert('first') }, function() { alert('second')} ];

Then a loop iterates through...

for ( var i = 0, l = handlers.length; i<l; ++i ) {
    handlers.apply( document, arguments )
}

And the functions are called in the context of the document.

meder
They're not handled quite like this, they're executed in a way that `jQuery(funcition($) { });` works :)
Nick Craver
it was a pseudo example, the `handlers` basically is `readyList`.
meder
@meder - I was referring to how they're being called :)
Nick Craver
A: 

This is not the better, but inside $(window).load you could have more control. after $(document).ready

$(window).load( fn );
Francisco Lavin