$(document).ready()与在正文末尾包含脚本之间的区别是什么? [英] What's the difference between $(document).ready() and including a script at the end of the body?

查看:158
本文介绍了$(document).ready()与在正文末尾包含脚本之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery的$ {document).ready()上执行JavaScript函数并将其包含在正文结尾处的HTML中的script标签之间,有什么区别?

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?

谢谢

DLiKS

推荐答案

<script>标记内的JavaScript代码将立即进行评估(执行).请注意,在这种情况下,页面尚未(全部)被解析,并且DOM尚未准备就绪.

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.

jQuery ready()回调中的JavaScript代码是在DOMContentLoaded事件上评估的,该事件在浏览器解析了整个HTML源代码之后发生.
关于此事件: https://developer.mozilla.org/en/Gecko-Specific_DOM_Events

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

此外,请查看以下SO问题,该问题指出了当您不使用就绪回调时会发生什么:

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?

这篇关于$(document).ready()与在正文末尾包含脚本之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆