JavaScript 代码优化:提高视频播放器控制栏交互性能
该代码段实现了当鼠标悬停在视频播放器控制栏上时,显示控制栏下方元素的功能。为了提高代码的性能和可维护性,可以考虑以下优化建议:
- 减少 DOM 查询次数: 代码中多次使用了
querySelector和querySelectorAll进行 DOM 查询,可以将这些查询结果存储在变量中,以减少查询次数,提高性能。例如:
let bottomItem = e.target.querySelector('.xg-inner-controls.xg-pos');
let copywriting = document.querySelector('[data-e2e="feed-active-video"] .tSXOCvQc');
- 减少样式操作: 在鼠标移动事件中,每次都对
bottomItem进行样式操作,可以考虑将样式操作合并为一次,在最后进行一次样式设置。例如:
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;
});
}
- 减少事件监听器: 代码中添加了多个事件监听器,可以考虑将一些事件合并为一个监听器,减少事件绑定和触发的次数。例如:
function handleMouseOver() {
cancelAnimationFrame(timeId);
showBottomItem();
}
function handleMouseLeave() {
hideBottomItem();
}
function handleMouseMove() {
if (!isShowing) {
showBottomItem();
}
}
e.target.addEventListener('mouseover', handleMouseOver);
e.target.addEventListener('mouseleave', handleMouseLeave);
e.target.addEventListener('mousemove', handleMouseMove);
- 避免重复绑定事件: 代码中,将监听器绑定到了
e.target和e.target的子元素上,可以考虑只绑定到e.target,然后通过event.target判断事件源。例如:
e.target.addEventListener('mouseover', function(event) {
if (event.target.classList.contains('xgplayer-controls')) {
// ...
}
});
- 使用节流函数: 在
mousemove事件处理函数中,可以使用节流函数来限制函数的执行频率,避免过多的函数调用。例如:
function throttle(func, wait) {
let timeout = null;
return function() {
let context = this;
let args = arguments;
if (timeout) return;
timeout = setTimeout(function() {
func.apply(context, args);
timeout = null;
}, wait);
};
}
let handleMouseMoveThrottled = throttle(handleMouseMove, 100);
e.target.addEventListener('mousemove', handleMouseMoveThrottled);
- 使用 requestAnimationFrame: 在
hideBottomItem函数中,使用了requestAnimationFrame来处理隐藏bottomItem的动画效果,可以考虑在showBottomItem函数中也使用requestAnimationFrame来处理显示bottomItem的动画效果,以提高性能和动画的流畅度。例如:
function showBottomItem() {
requestAnimationFrame(function() {
bottomItem.style.transition = 'all 0.3s';
bottomItem.style.bottom = '0px';
if (configxgIcon[4].option && copywriting) {
copywriting.style.display = 'none';
}
isShowing = true;
});
}
- 代码结构优化: 可以将一些重复的代码提取为函数,以增加代码的可读性和可维护性。例如:
function handleControlsMouseOver(event) {
if (event.target.classList.contains('xgplayer-controls')) {
// ...
}
}
e.target.addEventListener('mouseover', handleControlsMouseOver);
通过以上优化建议,可以有效提高视频播放器控制栏的交互性能,并使代码更加简洁易懂。
原文地址: https://www.cveoy.top/t/topic/pkjj 著作权归作者所有。请勿转载和采集!