Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
Kev Avatar asked Dec 17 '10 14:12

Kev


People also ask

Can we write document ready multiple times?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

Does document ready only run once?

$( document ). ready()ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Can you have nested document ready function?

Yes. you are right. The behaviour of second snippet is same with jQuery 2.1.

What is $( document ready () function Why should you use it?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.


1 Answers

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)

like image 50
David Tang Avatar answered Sep 23 '22 01:09

David Tang