javascript - 我应该把 jQuery 脚本标签放在哪里?

标签 javascript jquery

在所有文档中,我在 <title> 下面看到了 jQuery 脚本标记。但当我进入其他一些网站时( initializr 模板是我脑海中第一个出现的模板),它们将其放入正文的底部(你知道,就在 </body> 之前)。

这两个哪个是正确的?

最佳答案

引用 YDN Best Practices for Speeding Up Your Web Site :

Put Scripts at the Bottom

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

有趣的是人们过去常常这么说I should be slapped upside the head for doing thatI said that in 2009现在它突然成为一种最佳实践......取得了一些进展。

关于javascript - 我应该把 jQuery 脚本标签放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5046360/

相关文章:

javascript - 根据下拉列表的选择提交来自不同字段的数据 - laravel

javascript - 如何使用 yarn 工作区测试单个文件?

javascript - 将键和值拆分为单独的对象的有效方法是什么?

javascript - 在另一个函数中使用对象项

javascript - 如何使用表单中的隐藏字段获取发送的html页面内容

javascript - jQuery 没有选择所有的 div 标签

javascript - 使用 jsdom 和 Jest

javascript - $.when() 延迟数组

jquery - 列中的图像对齐

jQuery .css() 函数不适用于变量