使用被动监听器优化滚动体验

Published on Updated on

Translated to: English, Português, Pусский

触摸和滚轮事件监听器有利于跟踪用户交互和创建自定义滚动体验,但它们也可能会延迟页面滚动。目前,浏览器无法知晓事件监听器是否会阻止滚动,因此浏览器总是等待监听器完成执行后再滚动页面。被动事件监听器可以让您指示事件监听器永远不会阻止滚动,从而解决此问题。

浏览器兼容性

大多数浏览器都支持被动事件监听器。请参阅浏览器兼容性

Lighthouse 被动事件监听器审计失败的方法

Lighthouse 可以标记可能会延迟页面滚动的事件监听器:

Lighthouse 审计显示页面不使用被动事件监听器来提高滚动性能

Lighthouse 使用以下过程来识别可能影响滚动性能的事件监听器:

  1. 收集页面上的所有事件监听器。
  2. 筛选掉非触摸和非滚轮监听器。
  3. 筛选掉调用 preventDefault() 的监听器。
  4. 筛选掉来自与页面不同主机的监听器。

Lighthouse 会筛选掉来自不同主机的监听器,因为您可能无法控制这些脚本。可能存在损害页面滚动性能的第三方脚本,但这些脚本未在您的 Lighthouse 报告中列出。

Each Best Practices audit is weighted equally in the Lighthouse Best Practices Score. Learn more in The Best Practices score.

如何使事件监听器被动以提高滚动性能

为 Lighthouse 识别的每个事件监听器添加一个 passive 标志。

如果您只使用支持被动事件监听器的浏览器,则只需添加标志。例如:

document.addEventListener('touchstart', onTouchStart, {passive: true});

如果您支持的浏览器版本较旧,不支持被动事件监听器,则需要使用功能检测或 polyfill。有关更多信息,请参阅 WICG 被动事件监听器说明文档的功能检测部分。

资源

Updated on 改进文章

This site uses cookies to deliver and enhance the quality of its services and to analyze traffic. If you agree, cookies are also used to serve advertising and to personalize the content and advertisements that you see. Learn more about our use of cookies.