admin管理员组文章数量:1317904
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
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
Share Improve this question asked Jan 27, 2011 at 18:52 DLiKSDLiKS 1,5964 gold badges21 silver badges32 bronze badges3 Answers
Reset to default 7JavaScript 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/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?
- A script at the end of the body will run as soon as it is loaded.
- $.ready is executed after the document is plete (any linked css is also loaded).
- Body.load runs only when all images are loaded as well.
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.
本文标签:
版权声明:本文标题:javascript - What's the difference between $(document).ready() and including a script at the end of the body? - Stack Ov 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742031749a2416571.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论