Skip to content
学习 衡量 博客 Case studies 关于
本页内容
  • Lighthouse 被动事件监听器审计失败的方法
  • 如何使事件监听器被动以提高滚动性能
  • 资源

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

May 2, 2019 — 更新日期 Aug 28, 2019
Available in: Português, Русский, English
Appears in: 最佳做法审核
本页内容
  • Lighthouse 被动事件监听器审计失败的方法
  • 如何使事件监听器被动以提高滚动性能
  • 资源

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

浏览器兼容性 #

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

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 被动事件监听器说明文档的功能检测部分。

资源 #

  • 不使用被动监听器来提高滚动性能审计的源代码
  • 使用被动事件监听器提高滚动性能
  • 被动事件监听器说明文档
  • EventTarget.addEventListener()
Last updated: Aug 28, 2019 — Improve article
Return to all articles
分享
订阅

Contribute

  • 提交错误
  • 查看源代码

相关内容

  • developer.chrome.com
  • Chrome 动态
  • 网站开发基础
  • 案例研究
  • 播客
  • 节目

连接

  • Twitter
  • YouTube
  • Google Developers
  • Chrome
  • Firebase
  • Google Cloud Platform
  • 所有产品
  • 条款和隐私权
  • 社区准则

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies.