首页 > 解决方案 > 消除被动侦听器 JS 语法问题

问题描述

我正在尝试消除被动侦听器以提高滚动性能。但是每次我添加代码时,我的语法都会破坏我的主页滑块。这是我当前的集成语法:

<script>
function clean(node)
{
  for(var n = 0; n < node.childNodes.length; n ++)
  {
    var child = node.childNodes[n];
    if
    (
       child.nodeType === 8 
       || 
       (child.nodeType === 3 && !/\S/.test(child.nodeValue))
     )
     {
       node.removeChild(child);
       n --;
     }
     else if(child.nodeType === 1)
     {
       clean(child);
     }
   }
 }
 document.addEventListener("DOMContentLoaded", doClean);

 function doClean(){
     clean(document.body);
 }
 </script>

我试过添加:

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

这大大提高了我的页面分数。但就像我说的“它完全从主页上删除了我的滑块”。我想我只是没有正确编写 JS 语法。添加2“document.addEventListener”没有意义吗?有什么建议么?

我的网站:https ://www.staging3.easyimportauto.com/

谢谢

这就是我现在所处的位置(我有 2 个 EventListener):

document.addEventListener("DOMContentLoaded", doClean);

   function doClean(){
       clean(document.body);
}
document.addEventListener("touchstart", function(e) {
   console.log(e.defaultPrevented);  // will be false
   e.preventDefault();   // does nothing since the listener is passive
   console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: false});

上面的 JS 语法确实消除了 Google PageSpeed Insights 中的错误……但它仍然使我的 Revolution Slider/Banner 在主页上消失。我上面的代码一定还有错误吗?还是您认为这超出了被动侦听器添加的范围?嗯哈哈

我的网站:https ://www.staging3.easyimportauto.com/

标签: javascriptpassive-event-listeners

解决方案


推荐阅读