Tuesday, 11 February 2014

Multiple $(document).ready() sections.ready(function(){ … })



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:
$(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


No comments:

Post a Comment