Hendry H.
Hendry H.

Reputation: 1520

jquery document.ready multiple declaration

I realized that I can specify $(document).ready(function(){}); more than once.
Suppose like this

$(document).ready(function(){
    var abc = "1122";
    //do something..
});

$(document).ready(function(){
    var abc = "def";
    //do something..
});
  1. Is this standard ? Those codes work on my FF (16.0.2). I just a little afraid that other browser may not.
  2. What actually happen ? How jQuery handle those code ?

Thanks.

Upvotes: 4

Views: 1453

Answers (3)

just_a_dude
just_a_dude

Reputation: 2735

Even though it's standard, I'd rather use only one $(document.ready) ... to keep it DRY, otherwise you may end up with let's say 10 of these declarations on your page, which will make it look like unmaintanable spaghetti code (but JS allows you to do that too)

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382167

Yes, it's standard and recommended and jQuery guarantees those functions will be executed in order of declaration (see this related answer for details regarding the implementation).

The abc variable are local to your functions and don't interfere. You cannot see the value of abc declared in one of the callbacks from the other one.

Upvotes: 10

Manibhadra
Manibhadra

Reputation: 400

Yes, multiple document.ready function can be used in the same page. It will not going to give any error or exception in any browser. and the function will be executed for upper to lower order.

Upvotes: 1

Related Questions