Can you have multiple $(document).ready(function(){ ... }); sections?

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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!');
});

Solution 3 - Jquery

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

Solution 4 - Jquery

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)

Solution 5 - Jquery

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

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

//and

$("#mydiv").ready(function(){});

Solution 6 - Jquery

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

Solution 7 - Jquery

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.

Solution 8 - Jquery

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.

Solution 9 - Jquery

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.

Solution 10 - Jquery

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

Solution 11 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - Jquerykarim79View Answer on Stackoverflow
Solution 2 - JqueryMickelView Answer on Stackoverflow
Solution 3 - JquerypjesiView Answer on Stackoverflow
Solution 4 - JqueryJW.View Answer on Stackoverflow
Solution 5 - Jqueryuser142019View Answer on Stackoverflow
Solution 6 - JqueryJelle VerzijdenView Answer on Stackoverflow
Solution 7 - JqueryJames WisemanView Answer on Stackoverflow
Solution 8 - JqueryNeoView Answer on Stackoverflow
Solution 9 - JqueryNimantha Harshana PereraView Answer on Stackoverflow
Solution 10 - JqueryTimView Answer on Stackoverflow
Solution 11 - JqueryJEPriceView Answer on Stackoverflow