user2553512
user2553512

Reputation:

$.Document.Ready twice on same page , Which will execute first?

Guy's i am bit confused about the following code, in bellow code has two function then which will execute first Function1() or Function2 () ?

$(document).ready(function() {
  // some code here for function1()
});
$(document).ready(function() {
  // other code here for function2()
});

Upvotes: 2

Views: 1389

Answers (4)

Martin
Martin

Reputation: 3058

Both will be executed. You are registering events to trigger when document is ready. You can register more than one event for a given object, even if it's triggered by the same action.

Normally, I would expect the code that is declared first to trigger first, but I wouldn't write code that has dependencies in different blocks as it will be failure prone.

I would assume such a scenario in component based frameworks (like Wicket), where each component can have it's ready block, but if they are independant from each other, you wouldn't have to care about which one executes first.

If you have code where the execution order is an issue, I would recommend searching for some other approach to avoid this. As other answers have already stated, you can expect one order, but I wouldn't trust in all browser implementations, and worse than that, in future implementations.

So, as a general rule: keep things simple, if you need more than one event for one object it's fine as long as they're not dependant, else put them in the same block.

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150080

Function 1 will execute first. jQuery will always execute event handlers in the order they were bound (bearing in mind that delegated handlers will be executed after direct handlers because they only happen as the event bubbles up through the DOM - but that doesn't apply here).

This is documented in a parenthetical in the on method docs:

(Event handlers bound to an element are called in the same order that they were bound.)

Upvotes: 3

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

First function 1 will execute first, as jQuery always executes handlers as they were written

Plus

You can have as many of them as you wish, and they will be executed in the order that the $() or $(document).ready() functions are executed. (i.e. each handler is added to the queue)

Upvotes: 0

Aisha
Aisha

Reputation: 368

First document.ready will execute first.

Upvotes: 0

Related Questions