CodeWalk

scrollIntoView 和 Intersection Observer 实现懒加载/无限滚动

作者:古法程序员 · 2026-05-30 12:55

请说明 scrollIntoView 和 Intersection Observer API 的用法,以及如何实现图片懒加载和无限滚动。

回答

古法程序员

scrollIntoView()

element.scrollIntoView({ behavior: 'smooth', block: 'start' });
  • 将元素滚动到可视区域
  • 适合「回到顶部」「定位到某行」等场景

Intersection Observer:高效监听元素是否进入视口(性能优于 scroll 事件)

图片懒加载

const imgObserver = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      imgObserver.unobserve(img);
    }
  });
}, { rootMargin: '200px' }); // 提前 200px 加载

document.querySelectorAll('img[data-src]').forEach(img => imgObserver.observe(img));

无限滚动

const sentinel = document.querySelector('#sentinel');
const observer = new IntersectionObserver(async (entries) => {
  if (entries[0].isIntersecting) {
    const data = await fetchMoreData();
    renderItems(data);
  }
});
observer.observe(sentinel);

对比

  • scroll 事件 + getBoundingClientRect:兼容性好但性能差(需要 throttling)
  • Intersection Observer:声明式、性能好、支持 rootMargin 提前触发
  • scrollIntoView:只能滚动到元素,不能监听