Reputation: 1596
What's the difference between executing a JavaScript function on jQuery's $(document).ready() and including it in the HTML in script tags at the end of the body?
Thanks,
DLiKS
Upvotes: 5
Views: 1347
Reputation: 2139
This SO question might be helpful.
If you call a function in a script that is placed next to the closing body tag (</body>
) it's the same thing as using $(document).ready(function(){});
in the <head>
section.
Upvotes: 1
Reputation: 185933
JavaScript code inside the <script>
tags is evaluated (executed) immediately. Note that in this case the page has not been parsed yet (entirely), and the DOM is not yet ready.
JavaScript code inside the jQuery ready()
callback is evaluated on the DOMContentLoaded event, which occurs after the entire HTML source code has been parsed by the browser.
About this event: https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
Note that the modern way of defining the ready handler is this:
$(function() {
// code
});
Also, check out this SO question, which points out what happens when you don't use the ready callback: How many JavaScript programs are executed for a single web-page in the browser?
Upvotes: 7
Reputation: 116110
Upvotes: 3