JavaScript滚动条或其他事件监听时卡顿问题解决
问题定位追踪(此问题用户scroll事件举例)
window.addEventListener(‘scroll’, func)
此时监听时会导致鼠标一滚动就会被监听,极大的影响了页面的性能。
解决方法
防抖(debounce):
个人理解防抖主要就是通过定时器来限制页面事件监听处理次数。
上代码(项目中使用的代码仅限参考)
代码主要是通过滚动监听来控制nav导航的悬浮。
// 防抖函数
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var myEfficientFn = debounce(function() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var offsetTop = document.querySelector(’.hds_container’).offsetTop
if (scrollTop > 220) {
if (scrollTop > offsetTop) {
// true
if ($(’.m-header-fixed’).length != 0) {
$(".hds_container").removeClass(“isFixedNoTop”);
$(".hds_container").addClass(“isFixed”);
} else {
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").addClass(“isFixedNoTop”);
}
} else {
// false
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").removeClass(“isFixedNoTop”);
}
} else {
// false
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").removeClass(“isFixedNoTop”);
}
}, 100);
window.addEventListener(‘scroll’,myEfficientFn);