首页 > 解决方案 > 不使用被动侦听器来提高滚动性能(灯塔报告)

问题描述

最近的一份灯塔报告标记了以下问题。

不使用被动侦听器来提高滚动性能

它还提到...

考虑标记您的触摸和滚轮事件侦听passive器以提高页面的滚动性能。

我该如何解决这个问题?它似乎与jQuery有关。

标签: javascriptjquerylighthouse

解决方案


在 2016 年的https://github.com/jquery/jquery/issues/2871中有一个关于这个主题的长线程

简而言之:

  • jQuery 无法添加对被动侦听器的支持。
  • 预计这是在 jQuery 4 中添加的(4 年并且仍在
  1. 5.x)
  • 建议的修复是在 jQuery 加载后立即添加此代码:

jQuery.event.special.touchstart = {
        setup: function( _, ns, handle ){
            this.addEventListener("touchstart", handle, { passive: true });
        }
    };

2021 年更新:在 jquery 之后添加以下代码。这将修复它并删除 Pagespeed 警告

jQuery.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
jQuery.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
jQuery.event.special.wheel = {
    setup: function( _, ns, handle ){
        this.addEventListener("wheel", handle, { passive: true });
    }
};
jQuery.event.special.mousewheel = {
    setup: function( _, ns, handle ){
        this.addEventListener("mousewheel", handle, { passive: true });
    }
};

推荐阅读