Kev
Kev

Reputation: 119816

How many times can I have jQuery's document ready function declared on a page?

How many times is it permitted to have the jQuery document ready function declared on a page, i.e.:

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

or

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

Is there any difference between the two?

If it's permitted more than one, do they fire in order of declaration?

Upvotes: 20

Views: 9825

Answers (3)

Roy Tang
Roy Tang

Reputation: 5761

As many times as you like. They fire in order of declaration.

$(document).ready() will fire when the document is ready (when it's all loaded by the browser). The other one will fire as soon as that part of the script executes.

Upvotes: 2

David Tang
David Tang

Reputation: 93674

One: There is no difference between the two.

Quote:

All three of the following syntaxes are equivalent:

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

Two: You can have as many of them as you wish, and they will be executed in the order that the $() or $(document).ready() functions are executed. (i.e. each handler is added to the queue)

Upvotes: 21

Ryan Kinal
Ryan Kinal

Reputation: 17732

As many as you need.

The document ready function adds to what is essentially an event queue - the functions in these declarations will all be executed, either at the document.ready event, or immediately if that event has already fired, in order of declaration.

Upvotes: 13

Related Questions