Why "$().ready(handler)" is not recommended?

callback, document-ready, javascript, jquery

Solution

I got an official answer from one of the jQuery developers:

`$().ready(fn)` only works because `$()` used to be a shortcut to `$(document)` (jQuery <1.4) So `$().ready(fn)` was a readable code.

But people used to do things like `$().mouseover()` and all sorts of other madness. and people had to do `$([])` to get an empty jQuery object

So in 1.4 we changed it so `$()` gives an empty jQuery and we just made `$().ready(fn)` work so as not to break a lot of code

`$().ready(fn)` is literally now just patched in core to make it work properly for the legacy case.

The best place for the `ready` function is `$.ready(fn)`, but it's a really old design decision and that is what we have now.

I asked him:

Do you think that $(fn) is more readable than $().ready(fn) ?!

His answer was:

I always do $(document).ready(fn) in actual apps and typically there's only one doc ready block in the app it's not exactly like a maintenance thing.

I think $(fn) is pretty unreadable too, it's just A Thing That You Have To Know Works™...

Problem

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 ``` $().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`) and doesn't change or use the elements in the set. 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?

Original source

Related problems