Multiple $(document).ready()

read 36 comments

One more great thing about $(document).ready() that I didn't mention in my previous post is that you can use it more than once. In fact, if you don't care at all about keeping your code small, you could litter your javascript file with them.

It's great to be able to group your functions within a file or even across multiple files, and jQuery's flexible $(document).ready() function allows you to do that, pain free.

You could, for example, have one .js file that is loaded on every page, and another one that is loaded only on the homepage, both of which would call $(document).ready(). So, inside the <head> tag of your homepage, you would have three references to JavaScript files altogether, like so:

HTML:
  1. <script src="/js/jquery.js" type="text/javascript"></script>
  2. <script src="/js/common.js" type="text/javascript"></script>
  3. <script src="/js/homepage.js" type="text/javascript"></script>

You could also do something like this inside a single .js file:

JavaScript:
  1. $(document).ready(function() {
  2.   // some code here
  3. });
  4. $(document).ready(function() {
  5.   // other code here
  6. });

A final note: In a comment to my previous post, Jörn gave this excellent tip for shrinking your code:

Even for this little amount of code is a shortcut available:

$(function() {
// do something on document ready
});
A function passed as an argument to the jQuery constructor is bound to the document ready event.

Coming Up: In my next entry, I'll show how to do a simple effect with jQuery. You'll be amazed at how easy it is!

comment feed

36 comments

  1. Cool as it may look, it's also much less readable. The average Javascript programmer looking at the first example can at least guess that the code somehow creates a listener to the document ready 'event' (although I think there are lots that don't even know what that is), but the second example looks just abstract to anyone but jQuery insiders.

  2. Hi OddesE,

    Thanks for the comment! I assume that when you write, "Cool as it may look," you're referring to the shortcut above, $(function() { });, which I added to the entry in an update. If so, then I completely agree with you. Since writing this entry (over a year ago), I've standardized my own code to use the slightly more verbose, but much more readable $(document).ready(function() { });

  3. js

    This is exactly what I was looking for, but it seems as though I've ran into a limitation. You can't call a function defined within one $(document).ready() from the other $(document).ready().

    For example:

    $(document).ready(function() {
         var someFunction = function() {
              // some function that does stuff
         };
    });

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

    This will result in a "someFunction is not defined" error. Is there a way around this?

  4. I've been playing with jquery and json and am still a novice. I too wanted to use $(document).ready twice on the same page but couldn't get it to work. Then I tried to nest one inside the other and it works. Not sure if this is what your trying to do, but here is what I did.

    I have a select box on a page for choosing a customer. I use that to retrieve customer data. The returned data is used to build a small modify form with a "modify" button.

    my outer $(document).ready.... is for the the select box with id="cust_id". I use $.getJSON(....) to get the customer data and build a form from the returned data. My inner $(document).ready is used for the modify button (id="mod-btn"). It works.

    Code:

    
     $(document).ready(function(){
    	     $("#cust_id").bind("change", function(e){
    	        $("#filter-results").empty();
    			$("#results2").html("HELLO JOHN");
    		    $.getJSON("jquery-get-customer.php", {cust_id:$("#cust_id").val()}, function(data){
                             // data return code is here
                             // I build my form
                             $("#div-results").append("
                                      <form id=\"form2\"> + "<br />"
                                            // form elements here (removed for space)
                                            // the button...
    				   + "<input type=\"button\" id=\"mod-btn\" value=\"modify\"> <br />"
    				   + "</form>");
                              $(document).ready(function(){
    					  $("#mod-btn").click(function(){
    						  $.get("customers-modify.php", {
    							 // key:vals to be passed
    						   }, function(return_data){
    							   $("#results2").append(return_data);
    						   });
    					  });
    				  });   /*  inner $(document).ready  */
                });   /* getJSON  */
             });
         });   /*  outer $(document).ready   */
    

    Hope this helps.
    JohnC

  5. Thank you John Cowan so much
    I'm a Jquery newbie.
    I try to solve this problem for two day until i read your comment.
    It work very very perfect.
    Thank you again.

  6. I think you can add function names into $(document).ready instead of creating an anonymous inner function:

    
    $(document).ready(doSomething);
    function doSomething(){
        alert('Doing something');
    }
    
    
  7. Good call, Dave Yes, that's another way you can use the ready method.

  8. This is one of the best of jquery

  9. thanks of the info, the time where people were bothered with "body onload" is finished ^^ !

  10. ChrisQuery

    im trying to use document.ready and window.onload together in order to display a animated gif until the entire page is loaded, then hide the animated gif and show the content in an accordion that was loading.

    
    <script src="scripts/js/accordian-src.js"></
    script>
    <script src="scripts/js/jquery-1.2.6.min.js"></
    script>
    <script>
    $(document).ready(function(){
    $('div#basic-accordian').hide(); /* show gif */
    $('div#load').show(); /* hide accordion */
    });
    window.onload = function(){
    $('div#load').hide(); /* hide gif */
    $('div#basic-accordian').show('slow'); /* show accordion */
    new Accordian('basic-accordian',5,'header_highlight'); /* supposed to
    activate the accordion */
    }
    </script>
    

    the accordion loads but the accordions functionality is lost,
    new Accordian('basic-accordian',5,'header_highlight'); isnt read.
    if i remove all the jQuery and include the accordion loads fine and functional. If i remove all the accordion code the jQuery works fine...
    is there something wrong with my structure or could the accoridan code be conflicting with the jQuery include?
    thanks if anyone can help

  11. ChrisQuery

    in case anyone cares,

    i solved the issue using the jQuery.noConflict(); and then replacing all my jQuery $ with eg. jQuery(document).ready(function()
    there were a few $ symbols in the javascript code for the accordion.

    Im really liking this jQuery stuff!
    great blog, great books!

  12. Daniel LaLiberte

    I am getting inconsistent results trying to determine whether jQuery is ready. What is different for me is that I must load jQuery dynamically, with an injected SCRIPT tag, and I suspect that jQuery doesn't recognize that the document may be ready even before jQuery have been loaded, and in that case, jQuery.isReady never becomes true.

    Is there a simple reliable way of testing whether both the document is ready and jQuery is ready, regardless of the order in which they are loaded?

  13. Kevin of MO

    I'm working on a project where I need to collect data using AJAX prior to running some javascript in the body of my html. Do you have any ideas on how to load the header (on load), and waiting to load the rest of the page until the HttpRequest is returned and processed?

    Pseudo example:

    In header: initialization
    HttpRequest for dynamic menu data from MySQL
    Load other javascript/css
    In body: code for javascript menu (must be in the body), where menu data is from the HttpRequest

    Thanks for any advice,
    Kevin

  14. Hi I need to call another page and display it in a
    using jQuery with no onclick functions or anything
    just when the page loads display another page inside #mybox

  15. Why don't you use JQuery on this form that I'm writing this post!!!

    :)))

    tks

    • Hmm. I am using jQuery on this form. Notice the Live Comment Preview below? It uses jQuery. Notice the toolbar above? It uses jQuery, too. How else would you like me to use jQuery with the form? To "ajaxify" the submit? Certainly a possibility. One of these days...

  16. Thanks everyone for very very useful Javascript / jQuery insights in this blog.
    David Sawyer McFarland's Javascript Missing Manual book led me here.
    All these discussions are helping clarify the understanding I need to move on.
    I'm struggling a bit keeping cool while I get my head around programming in three different
    languages simultaneously: PHP to build the page on the server; Javascript to manage the user interactions and HTML and CSS to do the presentation ... no that's four 'languages'! With at least two execution models. But it all works very well .... mostly! except .... Q1) placement of Javascript code: I assume that (unlike PHP which is building HTML and Javascript all throughout the file) all Javascript has to live in the document head ... although I notice it does work if placed in the document body, I think some of my code's inconsistencies result from this .... can you explain / point me to an explanation of the exact sequence in which page loading / Javascript code execution takes place .... take a not-too-extreme example: my page with a form either receives 'execution control' via GET or POST ...but in both cases I assume the server is involved in rebuilding with PHP and then the client browser rebuilds and reloads Javascript afresh each time. Oh gosh this is too long a question!

  17. Rick

    This just is not working for me. I have 2 scripts with 2 separate $(document).ready(function) calls and only one is being executed. Is there something I'm missing?

    • Hi Rick,
      Are both scripts included after the core jQuery script? Is one of them throwing an error? Are both being loaded properly? Are you declaring a local variable in one and referring to it in the other? Firebug can help you track down the problem. Or, if you can provide a URL, I'll take a look for you.

  18. Hala

    hello everyhow,
    I have a problem, i was usuing the $(document).ready(function() {}); to load some jquery actions, however another javascript i adopted from the internet seems to conflict with it, it started giving me slider is null to the object i was trying to initialize in the ready function, and the object is there, and i need that script and also need to use the ready function, does anyone know how to solve this issue?
    Thanks,
    Hala

  19. Bryan

    Hello,
    I am a beginner in jQuery and I have been playing around with couple basic jQuery methods.
    A question came up when I try to build my test site, the scenario is as follows:
    If I have a site that includes only one javacript file, say site.js, and inside the file I have a couple of document.ready function that manipulates different DOM objects e.g.

    $(function(){
    //a function for sign_up page
    //change the border color when password field is unfocused
    $("#password").blur(function(){
    $("#password").css({"border" : "red solid 3px"});
    });

    //other functions
    });

    My question would be what if I am not in the page where the password field is present. Will this cause any problem or is this a good style? if not what would be a better approach?

  20. Dejan

    Hi Karl Swedberg.
    I'm noobie in JS and i have already integrated "easySlider" on my site for my photo gallery.
    I found out about "lavalamp" plug in and when i wanted to put it on same page as "easySlider" it's not working. So on other pages where i don't have "easySlider" everything is ok.
    I have no idea what to do.

    &lt pre &gt &lt code &gt
    $(function() {
    $("#1, #2, #3").lavaLamp({
    fx: "backout",
    speed: 700,
    click: function(event, menuItem) {
    return false;
    }
    });
    });

    $(document).ready(function(){
    $("#slider").easySlider({
    auto: false,
    continuous: true,
    numeric: true
    });
    });
    &lt /code &gt &lt /pre &gt

    I spended a whole night trying to fix this, but i had no luck (and knowledge as well).

    Any suggestion what to do?

    Thanks a lot in advance.

  21. tom

    hello, great article.
    wanted to ask a solution for the following scenario:
    i have a web page containing a div where i can drag and drop elements. On first time load, everything in .ready() in a script(lets call it script A) works great. Now i have another basic option besides the drag and drop to interact with the elements, and a refresh button to refresh the div asynchronously.
    The refresh button fetches all rows from database and places it in the div as draggables, but for them to become draggables, i need to echo script A again just after fetching them.
    Now i noticed that after each refresh, some items are firing more than 1 ajax request, as opposed to the first time page load without refreshing. Of course, if i dont "re echo" the script, i dont get draggables.
    Any suggestion welcome. Thanks.

    • Peter

      Just a guess, but you likely want to use unbind to remove the existing event handlers from the elements before you re-run Script A. Sounds like your elements have multiple handlers for a given event.

  22. Alex C

    Very nice! Exactly what I was looking for. I need this for a Joomla module which needs to generate some $(document).ready() code but not disturb the static call to the same function elsewhere. Thank you for this great article :)

  23. Hugo Ribeiro

    Ok, so here's my question...
    I am also trying to run a function within another, but I am having some(allot) of troubles...
    I've tryed this way:

    
    $(document).ready(function(){
    	$('#navmenu li a')
    		.css( {backgroundPosition: "-235px 0"} )
    		.mouseover(function(){
    			$(this).stop().animate({backgroundPosition:"(0px 0)", color:"#eee5e0"}, {duration:500})
    		});
    	$('#navmenu li a').mouseout(function(){
    			$(this).stop().animate({backgroundPosition:"(235px 0)", color:"#963231"}, {duration:200, complete:function(){
    				$(this).css({backgroundPosition: "-235px 0"})
    			}})
    		});
    	$('#navmenu li a').click( function(){
    			var href= $(this).attr('href');
    			var toLoad= href+' #texto';
    			var titulo = "\"O Artur\"";
    			if(href=="index.php")
    				titulo = "\"O Artur\""
    			else
    				titulo = $(this).text()
    			$('#texto').hide('normal',loadContent)
    			$('#load').remove()
    			$('#conteudo').append('LOADING...')
    			$('#load').fadeIn('normal')
    			$("p#titulo").fadeOut('fast')
    			window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-4)
    			function loadContent() {
    				$("#texto").load(toLoad,'',showNewContent())
    				$("p#titulo").html(titulo)
    				$("p#titulo").fadeIn("normal")
    			}
    			function showNewContent() {
    				$('#texto').show('normal',hideLoader())
    			}
    			function hideLoader() {
    				$('#load').fadeOut('normal')
    			}
    			return false;
    		});
    });
    $(document).ready(function(){
    	$("#datepicker").datepicker({ minDate: 0, maxDate: "+1Y" })
    });
    

    , and also with the following code inside the other... like this :

    
    $(document).ready(function(){
    (...)
            $(document).ready(function(){
    			$("#datepicker").datepicker({ minDate: 0, maxDate: "+1Y" })
           });
    });
    

    can anyone tell me what i am doing wrong?

    Thank you

    • Kavya Shetty

      var $j = {};
      $j = jQuery.noConflict(true);

      $j(document).ready(function () {
      $j(".newsticker").CarouselLite({
      });

      });
      $j(document).ready(function () {
      $('.slideshow').cycle({
      fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
      });
      });

    • Reinier Kaper

      The main problem in the first piece of code is that you declare functions within an anonymous function, you shouldn't do that.

      Take them out of there and declare them directly in the document ready part:

      $(document).ready(function() {
        function doSomething(args) {
          // Do something.
        }
        $('.some-element')
          .on('click', function() {
            // Call the doSomething function here.
            doSomething('foo');
          });
  24. I don't find using multiple domReady functions a good practice. This causes having multiple starting points for javascript that runs on a single page. For example if there is a code that manipulates DOM in both domReady functions, it could result in some error scenarios.

Sorry, but comments for this entry are now closed.