HOME> 世界杯比利时> Document:scroll 事件 - Web API

Document:scroll 事件 - Web API

由于 scroll 事件可被高频触发,事件处理器不应该执行高性能消耗的操作,如 DOM 操作。而更推荐的做法是使用 requestAnimationFrame()、setTimeout() 或 CustomEvent 给事件限流,如下所述。

然而需要注意的是,输入事件和动画帧的触发速度大致相同,因此通常不需要下述优化。此示例使用 requestAnimationFrame 优化 scroll 事件。

jslet lastKnownScrollPosition = 0;

let ticking = false;

function doSomething(scrollPos) {

// 利用滚动位置完成一些事情

}

document.addEventListener("scroll", (event) => {

lastKnownScrollPosition = window.scrollY;

if (!ticking) {

window.requestAnimationFrame(() => {

doSomething(lastKnownScrollPosition);

ticking = false;

});

ticking = true;

}

});