From the jQuery API docs site for ready
All three of the following syntaxes are equivalent:
- $ (document).ready(handler)
- $ ().ready(handler) (this is not recommended)
- $ (handler)
After doing homework – reading and playing with the source code, I have no idea why the
$ ().ready(handler)
is not recommended. The first and third ways, are exactly the same, the third option calls the ready function on a cached jQuery object with document:
rootjQuery = jQuery(document);
...
...
// HANDLE: $ (function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
But the ready function has no interaction with the selector of the selected node elements, The ready source code:
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
As you can see, it justs add the callback to an internal queue( readyList). this lets you call the ready function on every jQuery object.
Like:
- regular selector:
$ ('a').ready(handler)DEMO - Nonsense selector:
$ ('fdhjhjkdafdsjkjriohfjdnfj').ready(handler)DEMO - Undefined selector:
$ ().ready(handler)DEMO
Finally… to my question: Why $ ().ready(handler) is not recommended?