admin管理员组

文章数量:1326277

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.

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.

Share Improve this question asked Nov 29, 2012 at 10:17 Hendry H.Hendry H. 1,5203 gold badges14 silver badges28 bronze badges 1
  • Try this out – chridam Commented Nov 29, 2012 at 10:20
Add a ment  | 

3 Answers 3

Reset to default 10

Yes, it's standard and remended 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.

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.

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)

本文标签: javascriptjquery documentready multiple declarationStack Overflow