I always get confused by this when I'm working on large websites and am including a bunch of alien JS files and am trying to debug stuff.
If I have
<script type="text/javascript">
$(document).ready(function(){
console.log("foo");
});
$(document).ready(function(){
console.log("bar");
});
</script>
then does that guarantee console.log("bar") is triggered immediately after console.log("foo") ??? Is it the same if I have
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
where script1.js consists of
$(document).ready(function(){
console.log("foo");
});
and script2.js consists of
$(document).ready(function(){
console.log("foo");
});
What happens when I add window.onload and document.onload into the mix, e.g.
<script type="text/javascript">
$(document).ready(function(){
console.log("foo");
});
window.onload = function() { console.log("John Skeet"); };
$(document).ready(function(){
console.log("bar");
});
window.onload = function() { console.log("Bjarne Stroustrup"); };
</script>
?????
Can someone here explain, or lead me to the documentation that explains, the rule for how these "fire after everything else" functions get stacked?
They run synchronously.
That is to say they run in order:
1. console.log("foo"); //this gets first logged
2. console.log("John Skeet"); //this gets logged after "foo"
3. console.log("bar"); //this gets logged after "John Skeet"
4. console.log("Bjarne Stroustrup"); //this gets logged after "Bjarne Stroustrup"
So, they run synchronously unless you have asynchronous code.
For eg:
$(document).ready(function(){
setTimeout(function(){
console.log('foo');
}, 1000);
});
$(document).ready(function(){
setTimeout(function(){
console.log('bar');
}, 2000);
});
In my example of code, I've provided asynchronous code (setTimeout method), first 'bar' gets logged and there after 'foo' is logged.
So, the document ready handlers doesn't matters for ordering but matters with its synchronous/asynchronous code.
You may even be clear by seeing the code from jquery:
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
So, all ready handlers are pushed to the promises then calls its functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With