开发者

Guide on using jQuery $(function()) [closed]

Closed. This question is opinion-bas开发者_JAVA百科ed. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 6 years ago.

Improve this question

The statement $(function()) in jQuery is a shorthand for $(document).ready( ...

Does it make sense having just once at the beginning of the script portion and holding all the script code (as example within tags in a aspx page) as needed?

Or rather would it be better to replicate it more than once and containing each set logic of correlated code?

As example:

<script>
 $(function()
 {
    //script code for function 1
  });

 $(function()
 {
    //script code for function 2
  });
 </script>

Is there any "best practice" about it or are both approaches exaclty equivalent?


I would get functions off $(function(){});

Put there only function calling & doing other stuff.

function a(){
    alert('a');
}

function b(){
    alert('B');
}

$(function(){
    a();
    b();
});

multiple $(function(){}); calls are very expensive!

proof


Are they equivalent? No, since any variables you declared in one function are not accessible in another.

$(function() {
    var a = 3;
});
$(function() {
    $("#foo").text(a); // Undefined
});

Most of the time, that doesn't matter, though. And thus most of the time, having multiple calls to $(document).ready() is relatively harmless.

Don't do it repeatedly within a single file just to separate logical tasks. Have a single call to $(document).ready() whose callback calls other functions to handle those individual tasks.

But don't bend over backwards to avoid it either. If I have several files, or several libraries each requiring initialization, I don't hesitate to call $(document).ready() multiple times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜