Order of execution of jquery document ready

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.


Solution 1:

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.

Solution 2:

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.