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');
});

Answers


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.
});

This is shorthand for "document load" and also they've used the longhand "jQuery" with $ aliased inside to avoid collisions with other libraries using the $ sign.

If you don't wait for document load, things can get unpredictable/not work. Also if you have naming collisions, things will just plain blow up.


$(function() {}) is short for jQuerys document ready function http://api.jquery.com/jQuery/#jQuery3 and http://api.jquery.com/ready/ for more information


Copied and pasted directly from the docs:

jQuery( callback ) Returns: jQuery

Description: Binds a function to be executed when the DOM has finished loading.

version added: 1.0jQuery( callback )

`callback` The function to execute when the DOM is ready.

This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it.

Please review the api


It would depend on the context of the code, but there is a common design practice in JavaScript to encapsulate variables and methods within a Namespace or Module Pattern. This code may be a derivative of that intent.

The reasoning behind the Module Design Pattern boils down to complications with global variables and the dangers of 'clobbering'.

Clobbering can occur when any variable (or function) of the same name is defined twice. The second definition will override the first, and in essence clobber it.

Thus, it is a rule of thumb to wrap your code in a construct that shields your variables (and functions) from the global namespace. Douglas Crockford describes these type of scenarios well.

This example shows a slightly more common incarnation called 'closure':

var jspy = (function() {
    var _count = 0;

    return {
      incrementCount: function() {
        _count++;
      },
      getCount: function() {
        return _count;
      }
    };
})();

It is disorienting at first, but once you recognize it, it becomes second nature. The point is to encapsulate the _count variable as a private member to the returned object which has two accessible methods.

This is powerful because the global namespace now only includes one var (jspy) as opposed to one with two methods. The second reason that it is powerful is that it guarantees the _count variable can only be accessed by the logic in the two methods (incrementCount, getCount).

As I said, your code may be an incarnation of this rule of thumb.

Either way it is important to know this pattern in JavaScript because it opens the door to much more powerful interactions between frameworks, for example, and in asynchronous loading of them such as in AMD.

Here is a nice namespace example.

In summation, there is an advanced JavaScript Design Pattern that will help you to know, and the relevant terms are Module Pattern, Namespace Pattern. Additional associated terms are closure and AMD.

Hope that helps. All the best! Nash


This jQuery(function(){...} is a shorcut for jQuery(document).ready(function(){...}). Ready event is triggered when the DOM is ready so you'll be sure that you're not accessing something that is not available yet.

On the other hand, if you bind the click method as you do on your second snippet. That code will be executed right away, so you need to be sure that you place it after #saySomething declaration.


jQuery(function($) { ... }); is what prevents your code from executing until the DOM (HTML) is fully rendered and accessible.


If your jquery does not need the DOM to be fully loaded, you can safely use either form. To guarantee the DOM is fully loaded before executing your jquery, wrap your jquery statements in $(function....

$(function(){ ...}); is a shortcut for $(document).ready(function(){ ... }); https://stackoverflow.com/a/6454695/209942 http://jqfundamentals.com/chapter/jquery-basics

Jquery code wrapped in $(function won't get executed until all the HTML has been fully parsed into memory and the document is ready to be interacted with.

If, in your environment, the DOM is not guaranteed to be fully loaded before the renderer hits your jquery, and then you must wrap your jquery in $(function.

You can also try this alternate DOM-ready form, which makes $ a local variable, to avoid conflicts with other variables which possibly use $ symbol:

jQuery(function($){...}); https://stackoverflow.com/a/6454701/209942

If jquery code is NOT wrapped in $(function, will it work? If your DOM is loaded, then yes. DOM-loading depends on how you load your javascript. How to call a JavaScript function when the external JavaScript file is referenced at the end of the HTML body?

Be aware that this other, similar form, will NOT wait for the DOM to render. It's a function literal that is executed immediately. It doesn't have a leading $ or leading jquery, but does have trailing open+close parens:

(function(){...})();


Need Your Help

jQuery using .animate() fails to do ANYTHING in IE8

jquery internet-explorer internet-explorer-8 jquery-animate

So, it's official: I hate Internet Explorer. Yes, all bloody versions of it. :-D

Writing apps for Apple platforms with Javascript

javascript ios macos

Does Apple allow iOS and Mac apps to use Javascript? Can someone give me examples of how to use it and the advantages and disadvantages?