3

If have two javaScript functions in a page which are required to be called when document load is complete. Is is possible that any function can executed first or it will be the first function which is executed first always?

So if using jQuery if you have following code:

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

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

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Toseef Zafar
  • 1,601
  • 4
  • 28
  • 46

3 Answers3

7

jQuery ready uses the Deferred object system :

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

    return this;
},

(from the source code)

And the documentation states that

Callbacks are executed in the order they were added

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3

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

$(document).ready(function(){ 
    function1();
    function2();
});
Sebastian Breit
  • 6,137
  • 1
  • 35
  • 53
  • "I think it is possible, because the ready event is called asynchronusly" : That's just wrong. JQuery ensures the order of execution is the order of addition (see my answer). – Denys Séguret Oct 09 '12 at 09:55
  • I cant have these functions together because they are based on separate events in the page. so its possible that none of them, one of them or both of them appear in the document. – Toseef Zafar Oct 09 '12 at 11:46
0

Better make use of callback function to be sure about the execution order of the functions

prady00
  • 721
  • 1
  • 6
  • 17