coffeemonitor
coffeemonitor

Reputation: 13120

jquery document ready handler

Is there any difference between using:

$(document).ready(function(){

vs.

$(function(){

Does one of these work better than the other in some way, or is the first just a shorthand version of the first?

Upvotes: 5

Views: 1872

Answers (2)

Sarfraz
Sarfraz

Reputation: 382696

The latter is the short version of ready handler.

The:

$(function(){

})

is short version of this:

$(document).ready(function(){

}

Both do the same and one task.

jQuery is doing to a good deal with its slogan:

'Code less, do more'

Upvotes: 9

DannyLane
DannyLane

Reputation: 2096

From the docs:

All three of the following syntaxes are equivalent:

* $(document).ready(handler)
* $().ready(handler) (this is not recommended)
* $(handler)

There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed.

The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

HTH

Upvotes: 3

Related Questions