251

If I have a lot of functions on startup do they all have to be under one single:

$(document).ready(function() {

or can I have multiple such statements?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
leora
  • 188,729
  • 360
  • 878
  • 1,366

11 Answers11

307

You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:

http://www.learningjquery.com/2006/09/multiple-document-ready

Try this out:

$(document).ready(function() {
    alert('Hello Tom!');
});

$(document).ready(function() {
    alert('Hello Jeff!');
});

$(document).ready(function() {
    alert('Hello Dexter!');
});

You'll find that it's equivalent to this, note the order of execution:

$(document).ready(function() {
    alert('Hello Tom!');
    alert('Hello Jeff!');
    alert('Hello Dexter!');
});

It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:

$(document).ready(function() {
    alert('hello1');
    function saySomething() {
        alert('something');
    }
    saySomething();

});
$(document).ready(function() {
    alert('hello2');
    saySomething();
}); 

output was:

hello1
something
hello2
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 26
    It's not wise to rely on the order of execution when using multiple $(document).ready() statements. Each one needs to execute independently of any other having already been executed or not. – James Aug 25 '09 at 12:16
  • @AoP - I don't know how much sense that makes, if they are not executed in order, then they are completely meaningless within the context of the application, so using multiple $(document).ready( blocks would be broken altogether. – karim79 Aug 25 '09 at 23:18
  • 7
    @karim79 surely this (the OP's question) is most applicable when writing a complicated bit of code with multiple startup concerns - i.e. some code which is *always* run when loading completes, and some which is only required on some content nodes? In such a situation, the context should be silo'd, and order of execution should be immaterial - being able to assign to the 'DOM ready' event without overwriting the previous one becomes a useful feature, regardless of the ordering behaviour. – tehwalrus Apr 22 '12 at 21:47
  • Nice answer. I recently updated my jQuery UI tooltips for new versions of jQuery and jQueryUI and found I couldn't put the content in the title attribute anymore like I had (with HTML in it). I had to do it in jQuery tooltip() code. I was making a tooltip on every table row in a Java loop, so I ended up setting the content with some JS in a jQuery ready in each iteration as well. It isn't pretty but it worked. – Michael K Nov 01 '13 at 16:31
  • 1
    Regarding a function defined in one ready block not being callable from another ready block -- this is true the way you define the function, but if you instead define it as saySomething = function() {} then you can call it. Weird, right? http://jsfiddle.net/f56qsogm/ test it out here. – ferr Sep 05 '14 at 16:51
  • 3
    I think it behaves like this because it is adding the function to the window object which is accessible globally. Otherwise it is a declarative function scoped locally to that ready function. – ferr Sep 05 '14 at 17:00
18

You can use multiple. But you can also use multiple functions inside one document.ready as well:

$(document).ready(function() {
    // Jquery
    $('.hide').hide();
    $('.test').each(function() {
       $(this).fadeIn();
    });

    // Reqular JS
    function test(word) {
       alert(word);
    }
    test('hello!');
});
Mickel
  • 6,658
  • 5
  • 42
  • 59
  • This is ok if you have full control of the code attached to the page. If someone has already written this in another file attached to the page, then you're ok to declare it like this. – James Wiseman Aug 25 '09 at 11:55
  • Not sure what you are trying to say. But if you put this inside your head, and include 15 other external JS, all wich contains one (or multiple document.load) it will still work as if there was just one. Worth to mention is that the scoop of each function/variable ends with the closing bracket of the $(document).ready-function. – Mickel Aug 25 '09 at 12:08
  • 2
    Just trying to say that sometimes, other folk will have written modules attached to the page that have a document ready function already declared, so you mightn't have the luxury of moving all your code into one function (which, granted, would be ideal). I would also be wary of having too much stuff here however, as we'll get On Ready Bloating, which can make the code equally as hard to maintain. – James Wiseman Aug 25 '09 at 12:11
  • 1
    Ah, now I get you. Yeah I agree on that. Just stated an example to prove that it's possible ;) – Mickel Aug 25 '09 at 12:27
15

Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.

pjesi
  • 3,931
  • 3
  • 20
  • 16
10

Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)

JW.
  • 2,081
  • 1
  • 20
  • 24
  • Thanks, it's good to make this clear, since--despite the general wisdom on the subject--the [jQuery ready() page](http://api.jquery.com/ready/) doesn't actually say whether you can or not (at the time of writing :)). It does however kind of *imply* it's OK, if you read between the lines of one sentence: `Ready handlers bound this way are executed after any bound by the other three methods above.` – Reg Edit Aug 04 '14 at 09:27
5

Yes it is possible but you can better use a div #mydiv and use both

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

//and

$("#mydiv").ready(function(){});
  • 2
    Interesting idea, but why is it better? – Tim Apr 28 '14 at 16:46
  • 3
    Using a div is not supported. If for some reason you do this, you do so at your own risk: [The .ready() method can only be called on a jQuery object matching the current document](http://api.jquery.com/ready/) – Reg Edit Aug 04 '14 at 07:50
4

I think the better way to go is to put switch to named functions (Check this overflow for more on that subject). That way you can call them from a single event.

Like so:

function firstFunction() {
    console.log("first");
}

function secondFunction() {
    console.log("second");
}


function thirdFunction() {
    console.log("third");
}

That way you can load them in a single ready function.

jQuery(document).on('ready', function(){
   firstFunction();
   secondFunction();
   thirdFunction();

});

This will output the following to your console.log:

first
second
third

This way you can reuse the functions for other events.

jQuery(window).on('resize',function(){
    secondFunction();
});

Check this fiddle for working version

Community
  • 1
  • 1
Jelle Verzijden
  • 325
  • 3
  • 11
2

Yes you can.

Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.

Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • Yes, it's true, the functions are queued up rater than replacing previous $(document).ready functions. – Deeksy Aug 25 '09 at 12:11
2

Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.

Also you can not access some methods from another jQuery(function(){}); call so that's another reason you don't wanna do that.

With the old window.onload though you will replace the old one every time you specified a function.

Neo
  • 11,078
  • 2
  • 68
  • 79
0

It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.

0

You can even nest document ready functions inside included html files. Here's an example using jquery:

File: test_main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>
    <div id="main-container">
        <h1>test_main.html</h1>
    </div>

<script>
    $(document).ready( function()
    {
        console.log( 'test_main.html READY' );
        $("#main-container").load("test_embed.html");
    } );
</script>

</body>
</html>

File: test_embed.html

<h1>test_embed.html</h1>
<script>
    $(document).ready( function()
    {
        console.log( 'test_embed.html READY' );
    } );
</script>

Console output:

test_main.html READY                       test_main.html:15
test_embed.html READY                      (program):4

Browser shows:

test_embed.html

Tim
  • 1
  • 1
0

You can also do it the following way:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
     $("#hide").click(function(){
     $("#test").hide();
     });
     $("#show").click(function(){
     $("#test").show();
     });
 });
</script>
</head>

<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>

the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

JEPrice
  • 627
  • 7
  • 10
  • Can you describe how this different than the other answers? – Stephen Rauch Feb 01 '18 at 03:22
  • sure: the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had. – JEPrice Feb 01 '18 at 19:34
  • Sorry, I meant in the question. There is an edit button at the bottom left of the text box. Describing why your solution is different/better makes it a much better answer as future reader can more quickly understand the "Why". Thanks. – Stephen Rauch Feb 01 '18 at 19:36