start javascript code with $(function, etc

  1. $(document).ready(function(){}) ensures that your code runs on DOM ready, so that you have access to the DOM. You can read more about this in jQuery’s documentation.

  2. $(function(){}) is just an alias to #1. Any code in here will wait for DOM ready (see the docs).

  3. $(function($){}) is equivalent to #1 and #2, only you get a clean reference to jQuery in the local scope (see the note below). You can likewise pass in $ to the function in #1, and it’ll do the same thing (create a local reference to jQuery).

  4. (function(){}()) is just a self-executing-anonymous-function, used to create a new closure.

Please note that none of these are specific to Backbone. The first 3 are specific to jQuery, while #4 is just vanilla JavaScript.


Note: To understand what’s going on in #3 above, remember that $ is an alias to jQuery. However, jQuery is not the only library that uses the $ variable. Since the $ might be overwritten by someone else, you want to ensure that within your scope, $ will always reference jQuery – hence the $ argument.


In the end, it basically boils down to the following 2 options:

  1. If your JavaScript is loaded in the head, you have to wait for document ready, so use this:

    jQuery(function($) {
        // Your code goes here.
        // Use the $ in peace...
    });
    
  2. If you load your JavaScript at the bottom of your document (before the closing body tag – which you should definitely be doing), then there’s no need to wait for document ready (since the DOM is already constructed by the time the parser gets to your script), and a SEAF (A.K.A. IIFE) will suffice:

    (function($) {
        // Use the $ in peace...
    }(jQuery));
    

P.S. For a good understanding of Closures and Scope, see JS101: A Brief Lesson on Scope.

Leave a Comment