← 中文资源

简体中文版本

scrollend 事件取代滚动防抖

scroll 事件连续触发需要自己防抖,scrollend 在滚动完全停止后只触发一次,正是加载下一页的时机;本例注册两个事件并对比触发次数。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

scrollend needs a browser DOM with a scrollable #log-feed element

实现说明

逻辑集中在函数 attachFeedMonitoring里。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。

常见问题

「scrollend 事件取代滚动防抖」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

签名一览:function attachFeedMonitoring(scroller: HTMLElement)

核心语句

scroller.addEventListener("scrollend", () => {
  settled += 1;
  console.log(`scrollend #${settled} after ${scrollEvents} scroll events; append next page now`);
});
scroller.addEventListener("scroll", () => {
  scrollEvents += 1;
});

代码示例

// 'scroll' fires continuously while scrolling; the 'scrollend' event fires
// once, after scrolling has fully settled - so it replaces hand-rolled
// debounce timers when you only care about the resting position
let settled = 0;
let scrollEvents = 0;

function attachFeedMonitoring(scroller: HTMLElement): void {
  scroller.addEventListener("scroll", () => {
    scrollEvents += 1;
  });
  scroller.addEventListener("scrollend", () => {
    settled += 1;
    console.log(`scrollend #${settled} after ${scrollEvents} scroll events; append next page now`);
  });
}

if (typeof document === "undefined") {
  console.log("scrollend needs a browser DOM with a scrollable #log-feed element");
} else {
  const scroller = document.querySelector<HTMLElement>("#log-feed");
  if (scroller) {
    attachFeedMonitoring(scroller);
  }
  console.log("listener attached:", Boolean(scroller));
}