8

Are these both the same thing, i.e. ways of saying document ready:

$(function() {
  //
});

and

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

or is there a difference between the two, if so then when should I use which?

Sergio
  • 1,037
  • 1
  • 8
  • 5

3 Answers3

9

The first one is a shortcut for .ready().

The second one is simply invalid as you're trying to call a non-callable object.

You probably meant this:

// v--------no $ at the beginning
    (function( $ ) {

       // simply a new lexical environment with a 
       //        local $ parameter pointing to jQuery

    })(jQuery);

...though it has nothing to do with DOM ready.

There is a variation on your first example that combines the two:

jQuery(function( $ ) {

  // DOM ready, and creates a local $ parameter pointing to jQuery

});
user113716
  • 318,772
  • 63
  • 451
  • 440
1

They both are not same.

First code block is used to execute the function on document ready where as second code block is used when we want to execute the code block immediately without waiting for rest of the code to be loaded. But there is some error in your second part of the code. It should be as below.

(function($) {
   //
})(jQuery);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

This one is incorrect:

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

You're passing a function to $(...), then calling the result. However, the result of $(...) is a jQuery object, which is not a function. You might see it better this way:

$(

    function($) {
        //
    }

)

(jQuery);

Generally, there are three versions of document.ready, which are all equal to each other:

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

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

$().ready(function() {...});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • `$()` won't work in recent versions of jQuery (>= 1.4, IIRC), since those versions treat it as the empty selection, rather than selecting the document element. It's best avoided. – lonesomeday Aug 06 '11 at 22:40
  • 1
    @lonesomeday: You're probably right that it is best avoided (because it isn't officially supported), but it does work since jQuery's `.ready()` function currently ignores the `document` you pass to it. `$.fn.ready(...` and `$('MooTools').ready(func...` also work, but again are unsupported. – user113716 Aug 06 '11 at 22:52
  • @patrick dw: I'm not sure if they are 'unsupported' since even the docs say they can be used (with 'not recommended' added though). – pimvdb Aug 06 '11 at 22:56
  • @pimvdb: I think that's a fair point, but it seems silly for official docs to effectively say *"you can do this, but don't do this"*. That feels like its a minor update away from being unsupported. :) – user113716 Aug 06 '11 at 23:00