|
Post by account_disabled on Dec 26, 2023 1:17:48 GMT -6
消除低效的 JavaScript 第三个技巧是减少或消除网站中低效的 JavaScript :质量差的 JavaScript 会减慢网页速度,从而给用户带来糟糕和负面的体验。 我们可以在各种 PageSpeed Insights 报告中找到低效 JavaScript 的线索,最值得注意的是: 减少 JavaScript 执行时间,这会标记花费大量 CPU 时间解析或执行 JavaScript 代码的脚本。 消除渲染阻塞资源,包括可以在渲染页面之前执行的 JavaScript,从而使用户在看到任何内容之前等待更长时间。 Document.write 函数如果使用不当,可能会阻止其他操作的执行,从而导致页面出现严重的性能问题。例如,性能测试表明,通过 document.write 添加脚本 include 可以使网页的加载时间加倍,尤其是在慢速网络上。 不使用被动的听众;被动侦听器告诉浏览器 JavaScript 代码不会调用阻止滚动的函数,从而允许浏览器即使在 JavaScript 仍在运行时也可以滚动页面。 除了这些常见的例子之外,还有许多其他原因导致性能问题,“让 JavaScript 更高效是一个大话题,超出了本视频的范围,”Kent 承认。 为了消除无效代码,您通常必须以不同的方式重写 JavaScript,并且根据视频,网络上有许多可用的优质资源“描述了各种技术,从分析现 WhatsApp 号码数据 有代码到编写您自己的更强大组件的精简版本”。 删除未使用的 JavaScript 虽然从技术上讲它是低效 JavaScript 的一个子类别,但谷歌表示,网站上未使用的 JavaScript是一个很常见的问题,值得自己处理。 这种情况通常是由站点之间的代码重用引起的,这可能导致包含不必要的 JavaScript,因为“大多数网站不会使用库或框架提供的所有功能”或“您可以使用具有比必要功能更多的功能的组件” ”。 问题在于,插入从未被调用的 JavaScript 代码仍然需要 Web 浏览器下载并解析它,从而造成资源浪费。 为了检测网站上是否存在可能未使用的 JavaScript,我们可以再次使用 Google 的 PageSpeed Insights 报告,特别是以下部分: 减少未使用的 JavaScript,显示加载页面时未执行的 JavaScript。 避免巨大的网络负载,它通过解决大型库下载(这可能会导致巨大的网络负载)来确定需要改进的领域。 最大限度地减少主线程工作,其中包括解析、编译和执行 JavaScript 所花费的时间。 消除未使用的 JavaScript 可以降低这些成本,并且有一系列工具可以识别问题。例如,Kent 指出,诸如树摇动之类的技术可以识别从未在站点上调用的 JavaScript,因此可以从下载中删除。 树摇动可视化 但是,请注意不要忘记 JavaScript 的执行可能取决于环境因素:例如,在A/B 测试中,一段 JavaScript 只能由某些用户执行,在这种情况下,代码必须保留在网站上即使探查器报告它没有运行。 压缩 JavaScript 文件 非常直接的是 Google 的第五条建议,即确保下载时压缩JavaScript 文件,尤其是较大的文件。
|
|