什么是虚拟滚动?如何实现一个高性能的虚拟列表?

解读

在国内前端面试中,虚拟滚动是“性能优化”类的高频考点,尤其针对后台管理系统、聊天窗口、大数据表格等场景。面试官不仅想知道候选人“懂概念”,更关注“能落地”——即能否在真实业务里把 10 万条数据跑成 60 fps。回答时要体现三点:

  1. 原理一句话说清:只渲染可视区 + 缓冲区的少量 DOM,借助滚动偏移动态切片数据。
  2. 实现思路完整:从“度量、切片、定位、回收”四步闭环,到“高召回缓存、RAF 批量更新、事件节流、ResizeObserver”四项优化。
  3. 代码细节硬核:必须手写核心 50 行以内可运行版本,并指出坑位(动态行高、快速滚动白屏、内存泄漏、无障碍焦点丢失)。

知识点

  1. 渲染瓶颈:浏览器对 DOM 节点的布局、绘制、合成开销是 O(n),n 超过 1 k 就能感知掉帧。
  2. 滚动模型:scrollTop/scrollLeft 代表“卷去距离”,clientHeight 代表“可视高度”,scrollHeight 代表“总高度”。
  3. 切片算法:startIndex = floor(scrollTop / itemHeight),endIndex = startIndex + visibleCount + buffer,时间复杂度 O(1)。
  4. 动态行高:放弃固定 itemHeight,采用“前缀和数组 + 二分”或“预估高度 + 纠正偏移”双缓存策略。
  5. 高召回缓存:使用 LRU 或 IndexedDB 缓存已渲染节点尺寸,减少重复 measure。
  6. RAF 批量更新:把 scroll 事件收集到一帧内统一 setState,避免抢占主线程。
  7. 内存与焦点:节点回收时必须清理事件监听器,保留 aria-rowindex 保证读屏器焦点不跳变。
  8. 工程化:React 可用 react-window、vue 可用 vue-virtual-scroller,但二面常要求“不用第三方包手写”。

答案

// 固定行高版 50 行核心,可直接在浏览器跑
function VirtualList({
  data,              // 原始数组
  itemHeight,        // 单行高度
  containerHeight,   // 可视区高度
  renderItem         // 单行渲染函数
}) {
  const buffer = 5;  // 上下缓冲区
  const totalHeight = data.length * itemHeight;
  const visibleCount = Math.ceil(containerHeight / itemHeight) + buffer * 2;

  const container = document.createElement('div');
  Object.assign(container.style, {
    height: containerHeight + 'px',
    overflow: 'auto',
    position: 'relative'
  });

  const phantom = document.createElement('div');
  phantom.style.height = totalHeight + 'px';
  container.appendChild(phantom);

  const wrapper = document.createElement('div');
  Object.assign(wrapper.style, {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0
  });
  container.appendChild(wrapper);

  function update() {
    const scrollTop = container.scrollTop;
    const start = Math.floor(scrollTop / itemHeight) - buffer;
    const end = start + visibleCount;
    const offsetTop = Math.max(0, start * itemHeight);

    wrapper.style.transform = `translateY(${offsetTop}px)`;
    wrapper.innerHTML = '';
    for (let i = Math.max(0, start); i < Math.min(data.length, end); i++) {
      const node = renderItem(data[i], i);
      node.style.height = itemHeight + 'px';
      wrapper.appendChild(node);
    }
  }

  let rafId = null;
  container.addEventListener('scroll', () => {
    cancelAnimationFrame(rafId);
    rafId = requestAnimationFrame(update);
  }, { passive: true });

  update(); // 首屏
  return container;
}

// 使用示例
const list = VirtualList({
  data: Array.from({ length: 100000 }, (_, i) => ({ id: i, text: `第 ${i} 行` })),
  itemHeight: 40,
  containerHeight: 400,
  renderItem: (item) => {
    const div = document.createElement('div');
    div.textContent = item.text;
    div.style.boxSizing = 'border-box';
    div.style.borderBottom = '1px solid #eee';
    return div;
  }
});
document.body.appendChild(list);

动态行高升级思路(口述即可):

  1. 首次渲染时给未测量行设“预估高度”,渲染后取 getBoundingClientRect().height 存入 sizeMap。
  2. 维护前缀和数组 posMap,posMap[i] = posMap[i-1] + sizeMap[i-1]。
  3. scroll 时二分查找 scrollTop 对应索引,计算偏移量 offset = scrollTop - posMap[start]。
  4. 快速滚动出现白屏时,用 content-visibility: auto 或 IntersectionObserver 提前 300 ms 预渲染下一屏。
  5. 节点回收不销毁 DOM,而用 DocumentFragment 池化,减少 createElement 开销。

拓展思考

  1. 大数据表格:列也虚拟化(横向虚拟滚动),需要二维索引 + 网格缓存,阿里 Fusion、腾讯 TDesign 均用此方案。
  2. 协同编辑:虚拟列表与 OT 算法结合,光标位置需映射到“虚拟行号”,避免多人同时插入导致错位。
  3. 小程序/鸿蒙 JS 引擎:DOM 不存在,改用 scroll-into-view 与 recycle-view 组件,原理相同但度量单位用 rpx。
  4. 时间分片:数据量超 100 万,可在 Web Worker 做二分查找,主线程只负责渲染,减少 16 ms 卡帧。
  5. 无障碍合规:虚拟滚动必须同步设置 aria-setsize、aria-posinset,并在节点回收时把焦点托管到 aria-live 区域,否则读屏用户会“丢行”。