在页面底部编写脚本和在其中编写脚本有什么不同/优点/缺点

$(document).ready(function(){});

推荐答案

Very little in and of itself, either way the DOM will be ready for you to operate on (I was nervous about that until I read this from Google). If you use the end of page trick, your code may get called the slightest, slightest bit sooner, but nothing that will matter. But more importantly, this choice relates to where you link your JavaScript into the page.

如果您在head中包含script标签,并且依赖ready,那么浏览器在向用户显示任何内容之前会遇到script标签.在正常的事件过程中,浏览器突然停止并下载脚本,启动JavaScript解释器并将脚本交给它,然后等待解释器处理脚本(然后jQuery以各种方式监视DOM是否准备就绪).(我说"在正常情况下",因为有些浏览器支持script个标签上的async or defer个属性.)

如果在body元素的末尾包含script标记,浏览器不会完成所有这些操作,直到页面基本上已经显示给用户.这会提高页面的感知加载时间.

因此,要获得最佳的加载时间,请将脚本放在页面底部.(这也是the guideline from the Yahoo folks.)如果您要这样做,那么就不需要使用ready,当然,如果您愿意的话,也可以使用ready.

There's a price for that, though: You need to be sure that the things the user can see are ready to be interacted with. By moving the download time to after the page is largely displayed, you increase the possibility of the user starting to interact with the page before your script is loaded. That's one of the counter-arguments to putting the script tag at the end. Frequently it's not an issue, but you have to look at your page to see whether it is and, if so, how you want to deal with it. (You can put a small inline script element in the head that sets up a document-wide event handler to cope with this. That way, you get the improved load time but if they try to do something too early, you can either tell them that or, better, queue the thing they wanted to do and do it when your full script is ready.)

Jquery相关问答推荐

:eq Jquery,我似乎无法显示第一个之后的元素

将元素附加到每个函数 jQuery

Visual Studio - 将文本粘贴到 cshtml 中会删除文本

用 JS 触发 CSS 悬停

在文本框中的最后一个字符之后设置焦点

AngularJS 中的 ScrollTo 函数

在范围内设置文本

jQuery - 获取 ajax POST 的表单值

如何在 jQuery 中存储全局值(不一定是全局变量)?

Angular.js 在多个元素中重复

为什么找不到我的 json 文件?

使用 jQuery 从 AJAX 响应(json)构建表行

jquery变量语法

在jQuery中添加ID?

datatable jquery - 表头宽度与正文宽度不对齐

如何使用 Twitter Bootstrap 自动关闭alert

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

将多个 JavaScript 文件合并为一个 JS 文件

获取对象属性中的最小值/最大值的快速方法

jQuery - 不可见时获取元素的宽度(显示:无)