javascript 不使用被动侦听器来提高滚动性能(Lighthouse Report)[已关闭]

h7wcgrx3  于 2023-04-04  发布在  Java
关注(0)|答案(3)|浏览(101)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

2天前关闭。
截至2天前,社区正在审查是否重新讨论此问题。
Improve this question
最近的一份灯塔报告指出了以下问题。
不使用被动侦听器来提高滚动性能
它还提到...
考虑将触摸和滚轮事件侦听器标记为passive,以提高页面的滚动性能。
我该如何解决这个问题?它似乎与jQuery有关。

vfh0ocws

vfh0ocws1#

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

  • jQuery无法添加对被动侦听器的支持。
  • 预计这将在jQuery 4中添加(4年,仍在3.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 });
    }
};
2izufjch

2izufjch2#

这已经成功了!

// Passive event listeners
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") });
    }
};
dgiusagp

dgiusagp3#

如何使事件侦听器被动以提高滚动性能。要解决此问题-:
1.转到主题核心文件。
1.查找header.php,或者您可以使用插件将代码插入到标头中。
1.复制代码并粘贴到header.php文件中。
1.如果你打算在header.php中使用这些代码,我强烈建议你使用PHP的开始和结束标记。

<script>!function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){var e,t=["scroll","wheel","touchstart","touchmove","touchenter","touchend","touchleave","mouseout","mouseleave","mouseup","mousedown","mousemove","mouseenter","mousewheel","mouseover"];if(function(){var e=!1;try{var t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",null,t),window.removeEventListener("test",null,t)}catch(e){}return e}()){var n=EventTarget.prototype.addEventListener;e=n,EventTarget.prototype.addEventListener=function(n,o,r){var i,s="object"==typeof r&&null!==r,u=s?r.capture:r;(r=s?function(e){var t=Object.getOwnPropertyDescriptor(e,"passive");return t&&!0!==t.writable&&void 0===t.set?Object.assign({},e):e}(r):{}).passive=void 0!==(i=r.passive)?i:-1!==t.indexOf(n)&&!0,r.capture=void 0!==u&&u,e.call(this,n,o,r)},EventTarget.prototype.addEventListener._original=e}});</script>

相关问题