Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - multiple $(document).ready ...?

Question:

If I link in two JavaScript files, both with $(document).ready functions, what happens? Does one overwrite the other? Or do both $(document).ready get called?

For example,

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>  <script type="text/javascript" src="http://.../jquery1.js"></script>  <script type="text/javascript" src="http://.../jquery2.js"></script> 

jquery1.js :

$(document).ready(function(){     $("#page-title").html("Document-ready was called!"); }); 

jquery2.js:

$(document).ready(function(){     $("#page-subtitle").html("Document-ready was called!"); }); 


I'm sure it is best practice to simply combine both calls into a single $(document).ready but it's not quite possible in my situation.

like image 370
rlb.usa Avatar asked Mar 10 '11 17:03

rlb.usa


People also ask

Can you have multiple $( document .ready function ()?

ready' function in a page? Can we add more than one 'document. ready' function in a page? Yes we can do it as like I did in below example both the $(document).

Can I have multiple document .ready called in a single page?

The answer is that yes, it can be called multiple times. For example, you might have several Javascript library files and each of them may need to do something after the DOM has loaded. You could then easily put a $(document). ready() into each of them and they will all be run when the DOM's loaded.

Can you have nested document ready function?

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


2 Answers

All will get executed and On first Called first run basis!!

<div id="target"></div>  <script>   $(document).ready(function(){     jQuery('#target').append('target edit 1<br>');   });   $(document).ready(function(){     jQuery('#target').append('target edit 2<br>');   });   $(document).ready(function(){     jQuery('#target').append('target edit 3<br>');   }); </script> 

Demo As you can see they do not replace each other

Also one thing i would like to mention

in place of this

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

you can use this shortcut

jQuery(function(){    //dom ready codes }); 
like image 147
Praveen Prasad Avatar answered Sep 27 '22 19:09

Praveen Prasad


It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.

This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.

This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.

like image 45
cjastram Avatar answered Sep 27 '22 18:09

cjastram