Is there a difference between $ (). Ready () and $ (document) .ready ()

I saw some code where they only do this:

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

It's less than a document selector, but is it the same thing?

+26
jquery
Mar 05
source share
3 answers

Minor change:

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

It is equal to:

 $(function() {}); 

In jQuery 1.4: $().ready(function() { }); no longer works correctly in all cases. From the release notes:

As in jQuery 1.4, if you do not pass arguments to the jQuery () method, an empty jQuery set will be returned. In previous versions of jQuery, the collection containing the node document will be returned.

+30
Mar 05 '10 at 2:37
source share

Nick and Justin have the right answers here, but since we're on the topic, I would recommend for portability to never use $ in the global area. A few too many libraries use it for their own purposes, and you may run into compatibility issues if you need to mix them. Instead, you can use the optional first parameter for the jQuery handler:

 jQuery(function($) { }); 

This sets $ as a jQuery reference in this scope.

+8
Mar 05
source share

According to the jQuery API docs, all three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) (but this is not recommended)
  • $(handler)

Thus, it is obvious that the syntax will work, but is not the recommended syntax.

According to jQuery 1.4 Release Notes :

In jQuery 1.3, jQuery () returned a jQuery set containing only a document. in jQuery 1.4 it returns an empty jQuery set. This can be useful for creating an empty set and adding elements to it dynamically. Note. JQuery () method. Ready () still works in version 1.4, but it is deprecated. Use jQuery (document) .ready () or jQuery (function () {}).

+7
Mar 05 '10 at 2:40
source share



All Articles