Calling $(document).ready multiple times with jQuery

Posted in Javascript -

jQuery's $(document).ready() function runs the code within that function after the DOM is loaded (I've written about this previously here). Something I haven't needed to do before, but was wondering if it's possible, is to use $(document).ready() more than once.

Calling $(document).ready() multiple times

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.

To check this works I created the following page:

    <script language="javascript" src="/js/jquery-1.3.2.min.js"></script>
    <script language="javascript" src="/js/test1.js"></script>
    <script language="javascript" src="/js/test2.js"></script>


test1.js contained the following:

$(document).ready(function() {

test2.js contained the following:

$(document).ready(function() {

Sure enough, I got two alert dialogs with the text "1" and then "2".

Related posts: