Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution of jquery document ready

Tags:

jquery

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.

like image 615
Amrit Avatar asked Oct 14 '10 15:10

Amrit


People also ask

What is document ready in jQuery?

jQuery ready() MethodThe ready event occurs when the DOM (document object model) has been loaded. Because this event occurs after the document is ready, it is a good place to have all other jQuery events and functions.

How does jQuery ready work?

The jQuery document ready function executes when the DOM (Document Object Model) is completely loaded in the browser. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery. The Javascript/jQuery code inside the $(document).

What is difference between $( function () and document Ready?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

Which jQuery function can you use to execute when the document finished loading?

ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.


2 Answers

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.

like image 68
Nick Craver Avatar answered Sep 20 '22 23:09

Nick Craver


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.

like image 27
meder omuraliev Avatar answered Sep 21 '22 23:09

meder omuraliev