$(document).ready()之间有什么区别,并在主体的末尾包含一个脚本? [英] What's the difference between $(document).ready() and including a script at the end of the body?

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

问题描述

在jQuery的$(document).ready()上执行一个JavaScript函数,并将它包含在HTML脚本标签中,并将其包含在body标签的末尾之间有什么区别?

感谢,

DLiKS

解决方案

立即评估(执行)code>< script> 标签。请注意,在这种情况下,页面尚未完全解析,并且DOM尚未准备好。



jQuery中的JavaScript代码 ready() callback在DOMContentLoaded事件上进行评估,该事件在整个HTML源代码已被浏览器解析后发生。

关于此事件: https://developer.mozilla.org/zh/Gecko-Specific_DOM_Events p>

请注意,定义处理程序的现代方式是这样的:

  $(function(){
// code
});

另外,看看这个SO问题,它指出了当你不使用ready回调:多少JavaScript程序是针对浏览器中的单个网页执行的?


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

解决方案

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?

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

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