Why do I encapsulate a jQuery function within jQuery(function ($) { });

I came across a piece of code which looks like this:

jQuery(function($) {
  $('#saySomething').click(function() {
    alert('something');
  });
});

I don't quite get it. Why can't I simply do this:

$('#saySomething').click(function() {
   alert('saySomething');
});

jQuery(function ($) {...});

is the shorthand version of:

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

If you don't wait for the document to be ready, the elements that you'd bind events on won't exist in the dom, and the events wont actually be bound.

Alternatively you could wait for the body to have finished loading, however that will include waiting for images, which take longer to load.

Truth be told, you don't have to wait for document.ready . You can go ahead and use $('#saySomething').click(...) if you know the element exists in the DOM:

<button id="saySomething>Say Something!</button>
<script>
    jQuery('#saySomething').click(...);
</script>

There is one last nuance to jQuery(function ($) {...}); that you should know about. The $ parameter in the function is used to alias jQuery to $ , which will allow you to use the $ shorthand within the function without having to worry about conflicts with other libraries (such as prototype).

If you're not waiting for document.ready it's common to see an IIFE used to alias jQuery:

(function ($) {
    $('#saySomething').click(...);
}(jQuery));

jQuery(function($) {

is a shortcut for

jQuery(document).ready(function(){

This waits until the document is in a "ready" state where the DOM is built. You jQuery scripts can then work with the complete page and not miss any elements.

But - you can run jQuery without it. If you script is in the head, you run the risk of selecting for elements that haven't been created yet. I have used jQuery in the body of my document immediately after the element(s) I want to affect in an attempt to operate on them as soon as I possibly could. That was an unusual case and I typically don't do it.

Another reason to use the ready function - you can run it more than once. If you include multiple scripts or you have code that's conditionally included, you can have multiple ready() functions. The code in each ready block is held until the ready state is achieved, and then the code is executed in the order it was added.


The first example gets exectuted after the page is fully loaded. The second example gets executed directly (and will probably fail).

So, the first is a shorthand for:

$(document).ready(function(){
  // Do something after the page is loaded.
});
链接地址: http://www.djcxy.com/p/17066.html

上一篇: 定义函数的最佳方法是什么?

下一篇: 为什么我在jQuery中封装jQuery函数(function($){});