贝利信息

JavaScript中如何实现虚拟列表_滚动性能优化

日期:2025-12-16 00:00 / 作者:幻影之瞳
虚拟列表是只渲染可视区域及缓冲区节点、用空白占位其余项的技术,用于解决大数据量列表的卡顿、高内存和滚动不流畅问题;通过计算滚动位置下的起始/结束索引截取数据,并用 translateY 偏移整体列表实现视觉对齐。

什么是虚拟列表,为什么需要它

当列表数据量很大(比如上万条),直接渲染所有 DOM 节点会导致页面卡顿、内存占用高、滚动不流畅。虚拟列表只渲染当前可视区域及其少量缓冲区内的节点,其余节点用空白占位,从而大幅减少 DOM 数量和重排重绘开销。

核心实现思路:只渲染“看得见”的部分

关键在于计算:当前滚动位置下,哪些数据项在视口内?它们应渲染在什么位置?

简单可运行示例(固定高度 item)

假设每条数据高度为 50px,容器高 400px,总数据 10000 条:

const container = document.getElementById('list');
const itemHeight = 50;
const visibleCount = Math.ceil(400 / itemHeight); // 约 8 条
let startIndex = 0;

container.addEventListener('scroll', () => { const scrollTop = container.scrollTop; startIndex = Math.floor(scrollTop / itemHeight); const endIndex = Math.min(startIndex + visibleCount + 2, listData.length); // +2 是缓冲

// 渲染 slice 后的 items,并设置 wrapper 的 translateY const fragment = document.createDocumentFragment(); const renderList = listData.slice(startIndex, endIndex); renderList.forEach((item, i) => { const el = document.createElement('div'); el.textContent = item; el.style.height = ${itemHeight}px; fragment.appendChild(el); }); listWrapper.innerHTML = ''; listWrapper.appendChild(fragment); listWrapper.style.transform = translateY(${startIndex * itemHeight}px); });

进阶优化点

真实项目中还需考虑这些细节:

基本上就这些。不复杂但容易忽略缓冲区、transform 定位和高度缓存——做好这三点,万级列表也能丝滑滚动。