Question

I've seen four different ways to tell jQuery to execute a function when the document is ready. Are these all equivalent?

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

$().ready(function () {
  alert('$().ready()');
}); 

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

jQuery(function ($) {
  alert('jQuery()');
}); 
Was it helpful?

Solution

There is no difference.

$ is the same as jQuery. If you view the unminified source, you will see var $ = jQuery = ... or something to that effect.

The jQuery function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)

Calling jQuery without a parameter defaults to using document. So $() and $(document) are identical. Try it in Firebug.

OTHER TIPS

re: Geroge IV's comments regarding $() == $(document) its correct. From the unminified source (init is what get called internally):

init: function( selector, context ) {
    // Make sure that a selection was provided
    selector = selector || document;

Also from source, to back up previous conversations:

// HANDLE: $(function)
    // Shortcut for document ready
    } else if ( jQuery.isFunction( selector ) )
        return jQuery( document ).ready( selector );

this should be community wiki. I've always been interested in the inner workings of jquery, now I've had an excuse to start looking :-)

Also it should be mentioned, that symbol that you pass to function will be use inside the function. For example:

$(function(jQuery) {
   // now I can use jQuery instead $
   jQuery("body").append("<div></div>"); // adds div to the end of body element
}); 

if you want use $ - you can leave function's param in this situation empty

The real example you can find here http://jsfiddle.net/yura_syedin/BNgd4/

Here's another one - starts like this...

(function (jQuery) {

then to finish...

})(jQuery);

An example is here: http://jsfiddle.net/C2qZw/23/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top