JQuery callback order

If the page has two javaScript functions that should be called when the document is loaded. Is it possible that any function can be executed first or will it be the first function that is always always executed?

So, if you are using jQuery, if you have the following code:

$(document).ready(function(){ function1(); }); $(document).ready(function(){ function2(); }); 

Could it happen that function2 is executed first or will function1 always be executed first?

+3
source share
3 answers

jQuery ready uses the Deferred Object System :

 ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, 

(from source )

And the documentation states that

Callbacks are executed in the order in which they were added.

So yes, your callbacks will be executed in the order of addition.

+7
source

If you want these functions to be executed in order, why don't you just write:

 $(document).ready(function(){ function1(); function2(); }); 
+3
source

It is better to use a callback function to be sure of the order in which the functions are executed.

0
source

All Articles