gpt4 book ai didi

javascript - 如果脚本确实很短,那么使用内联 JavaScript 是否优于外部包含?

转载 作者:行者123 更新时间:2023-12-03 21:46:26 24 4
gpt4 key购买 nike

我在网站中使用外部 JavaScript,因为我总是尝试将 JavaScript 保留在底部和外部。

但是Google page speed正在给出这个建议

The following external resources have small response bodies. Inlining the response in HTML can reduce blocking of page rendering.

http://websiteurl/ should inline the following small resources: http://websiteurl/script.js

这个外部js文件只有这个内容

$(document).ready(function() {
$("#various2").fancybox({
'width': 485,
'height': 691,
});
});

但是在 Yslow 我得到了这个建议

对“将 JavaScript 和 CSS 外部化”评分为不适用

Only consider this if your property is a common user home page.

There are a total of 3 inline scripts

JavaScript and CSS that are inlined in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.

Google 和雅虎哪个是正确的?

最佳答案

这在很多方面都是一个有点问题的例子。

您可以以不需要内联 JS 的方式组织脚本。例如,您可以有一个 common.js 文件来运行该代码片段、其他类似的代码片段并简化您的代码。

此外,这似乎唤醒了“永远不要内联任何 JavaScript”架构警察。事实证明,有时内联 JavaScript 是最佳实践,例如查看 Google 分析中的常见片段。

为什么是Google suggesting你应该内联这个小脚本吗?

  • 因为20% of the page visits你会得到一个未启动的缓存
  • 如果出现缓存未命中,则可能需要打开与您网站的新连接(1 个往返),然后在第 2 个往返中传送数据。 (如果幸运的话,您可以使用 keepalive 连接,并且它被削减为 1 次往返。
  • 对于一般的“全局”英语网络应用程序,您会看到美国托管的服务的典型往返时间为 110 毫秒。如果您使用 CDN,数量可能会减半。
  • 即使资源位于本地,网络浏览器可能仍然需要访问磁盘才能获取该小文件。
  • 非异步或延迟 JavaScript 脚本标记是阻塞的,如果此脚本位于页面中间的某个位置,它将卡在那里,直到脚本下载为止。

从性能 Angular 来看,如果只有两个选项:

  1. 内联放置 50 个字符的 JavaScript 位
  2. 将 50 个字符放入单独的文件中并提供服务。

考虑到您是一个优秀的网络公民并压缩了所有内容,与给人们带来相当大的延迟的 20% 风险相比,这增加的额外有效负载量可以忽略不计。我总是会选择#1。

在一个不完美的世界中,很少有如此清晰且简单的选项。有一个选项 3,涉及异步加载 jQuery 并从公共(public)区域获取此功能。

关于javascript - 如果脚本确实很短,那么使用内联 JavaScript 是否优于外部包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7205225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com