优化 JavaScript 代码以提高性能和效率

这篇文章展示了如何优化一段 JavaScript 代码,以提高其性能和效率。代码的目的是在鼠标悬停在 'xgplayer-controls' 元素上时显示一个底部元素,并在鼠标移开时隐藏该元素。

原代码

document.addEventListener('mouseover', function(e) {
  if (e.target.classList.contains('xgplayer-controls')) {
    let bottomItem = e.target.querySelector('.xg-inner-controls.xg-pos');
    let copywriting = document.querySelector('[data-e2e="feed-active-video"] .tSXOCvQc');
    let timeId = null;

    function showBottomItem() {
      bottomItem.style.transition = 'all 0.3s';
      bottomItem.style.bottom = '0px';
      if (configxgIcon[4].option && copywriting) {
        copywriting.style.display = 'none';
      }
    }

    function hideBottomItem() {
      clearTimeout(timeId);
      timeId = setTimeout(function() {
        if (configxgIcon[4].option) {
          bottomItem.style.bottom = -bottomItem.offsetHeight + 'px';
        }
        if (!configxgIcon[0].option && copywriting) {
          copywriting.style.display = '';
        }
      }, 1000);
    }

    e.target.addEventListener('mouseover', function() {
      clearTimeout(timeId);
    });

    e.target.addEventListener('mouseleave', hideBottomItem);

    showBottomItem();
  }
});

优化方案

此段代码的优化方案包括以下几点:

  1. 缓存 DOM 元素: 将需要频繁使用的 DOM 元素缓存起来,减少重复查询 DOM 的开销。
  2. 减少重复操作: 在 showBottomItem 函数中,如果 configxgIcon[4].option 为真,每次都会隐藏 copywriting 元素,可以将其放在判断条件外面,避免重复操作。
  3. 使用 requestAnimationFrame 优化动画效果:bottomItem 的显示和隐藏放在 requestAnimationFrame 中执行,可以提高动画效果的性能。
  4. 使用事件委托:mouseovermouseleave 事件委托给父元素,这样可以减少事件绑定的数量。

优化后的代码

document.addEventListener('mouseover', function(e) {
  if (e.target.classList.contains('xgplayer-controls')) {
    let bottomItem = e.target.querySelector('.xg-inner-controls.xg-pos');
    let copywriting = document.querySelector('[data-e2e="feed-active-video"] .tSXOCvQc');
    let timeId = null;
    let isShowing = false;

    function showBottomItem() {
      bottomItem.style.transition = 'all 0.3s';
      bottomItem.style.bottom = '0px';
      if (configxgIcon[4].option && copywriting) {
        copywriting.style.display = 'none';
      }
      isShowing = true;
    }

    function hideBottomItem() {
      cancelAnimationFrame(timeId);
      timeId = requestAnimationFrame(function() {
        if (configxgIcon[4].option) {
          bottomItem.style.bottom = -bottomItem.offsetHeight + 'px';
        }
        if (!configxgIcon[0].option && copywriting) {
          copywriting.style.display = '';
        }
        isShowing = false;
      });
    }

    e.target.addEventListener('mouseover', function() {
      cancelAnimationFrame(timeId);
    });

    e.target.addEventListener('mouseleave', hideBottomItem);

    function handleMouseMove() {
      if (!isShowing) {
        showBottomItem();
      }
    }

    e.target.addEventListener('mousemove', handleMouseMove);
  }
});

总结

通过以上优化,可以减少不必要的 DOM 查询和重复操作,提高代码的性能和效率。

优化 JavaScript 代码以提高性能和效率

原文地址: https://www.cveoy.top/t/topic/pkiR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录