Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about multiple ready()'s

Tags:

Suppose I have:

<script src="script1.js"></script> <script src="script2.js"></script> 

Both of these scripts have ready() inside. Will the code in script2.js's ready() always execute after the first one?

like image 312
bgcode Avatar asked Jul 10 '11 19:07

bgcode


People also ask

Can we have multiple document ready function?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

How many times can we use $( document ready () in page in JavaScript?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

Why do we use document ready?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

What is difference between document ready and document load?

load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.


2 Answers

Yes.

First of all, the code in script2.js will be executed after script1.js, as it comes later in the document (and the defer attribute is not set).

Furthermore, the implementation [source] of the ready function is:

ready: function( fn ) {     // Attach the listeners     jQuery.bindReady();      // Add the callback     readyList.done( fn );      return this; }, 

where readyList seems to be [source] a deferred object [docs]. That means the callbacks are executed in the order they have been added to that object.

like image 168
Felix Kling Avatar answered Sep 22 '22 02:09

Felix Kling


jQuery uses its own Deferred object for this. The appropriate code of jQuery proves that it is executed in order:

When you call .ready, the function is added to the readyList:

readyList.done( fn ); 

When the DOM is ready, this function is executed:

readyList.resolveWith( document, [ jQuery ] ); 

The resolveWith function contains this code which executes the functions added as callbacks:

while( callbacks[ 0 ] ) {     callbacks.shift().apply( context, args ); } 

As you can see, the callback functions are shifted (popped out from the beginning of the callback array (i.e., readyList)), so the first gets executed before the second.

like image 36
pimvdb Avatar answered Sep 19 '22 02:09

pimvdb