一次性渲染 10,000+ 行 <tr> 會導致:
虛擬滾動 核心思想:**只渲染可視區域內的行(約 20-50 行)**,滾動時動態替換內容,配合高度撐開的占位容器模擬原生滾動條。
class VirtualScrollTable {
constructor(options) {
this.data = options.data || []; // 完整數據陣列
this.rowHeight = options.rowHeight || 30; // 固定行高(關鍵)
this.container = document.getElementById(options.containerId);
this.tableBody = this.container.querySelector('tbody');
this.viewportHeight = options.viewportHeight || 300;
this.visibleCount = Math.ceil(this.viewportHeight / this.rowHeight) + 2; // 緩衝區
this.scrollTop = 0;
this.startIndex = 0;
this._initDOM();
this._bindEvents();
this.render();
}
_initDOM() {
// 1. 外層滾動容器
this.scrollWrapper = document.createElement('div');
this.scrollWrapper.style.cssText = `
height: ${this.viewportHeight}px;
overflow-y: auto;
position: relative;
`;
// 2. 撐開高度的內容占位器
this.spacer = document.createElement('div');
this.spacer.style.height = `${this.data.length * this.rowHeight}px`;
this.scrollWrapper.appendChild(this.spacer);
// 3. 固定表頭 + 可滾動 tbody
this.container.innerHTML = '';
this.container.appendChild(this.scrollWrapper);
// 表頭固定(簡化:這裡用 sticky)
const table = this.container.querySelector('table') || document.createElement('table');
table.style.borderCollapse = 'collapse';
table.innerHTML = `
${this._renderHeader()}
`;
table.querySelector('thead').style.position = 'sticky';
table.querySelector('thead').style.top = '0';
table.querySelector('thead').style.background = '#f5f5f5';
table.querySelector('thead').style.zIndex = '1';
this.scrollWrapper.appendChild(table);
this.tableBody = table.querySelector('tbody');
}
_bindEvents() {
this.scrollWrapper.addEventListener('scroll', () => {
this.scrollTop = this.scrollWrapper.scrollTop;
this._calculateRange();
this.render();
});
}
_calculateRange() {
this.startIndex = Math.floor(this.scrollTop / this.rowHeight);
this.startIndex = Math.max(0, Math.min(this.startIndex, this.data.length - this.visibleCount));
}
render() {
const fragment = document.createDocumentFragment();
const end = Math.min(this.startIndex + this.visibleCount, this.data.length);
for (let i = this.startIndex; i < end; i++) {
const row = this._createRow(this.data[i], i);
fragment.appendChild(row);
}
this.tableBody.innerHTML = '';
this.tableBody.appendChild(fragment);
// 關鍵:調整 spacer 的 margin-top 而非 height,避免重排
this.spacer.style.marginTop = `${this.startIndex * this.rowHeight}px`;
}
_createRow(item, index) {
const tr = document.createElement('tr');
tr.style.height = `${this.rowHeight}px`;
tr.innerHTML = `${item.id} ${item.text} `;
return tr;
}
_renderHeader() {
return 'ID Text ';
}
// 公開方法:數據更新
setData(newData) {
this.data = newData;
this.spacer.style.height = `${newData.length * this.rowHeight}px`;
this._calculateRange();
this.render();
}
}
// 初始化:生成 10000 條測試數據
const testData = Array.from({ length: 10000 }, (_, i) => ({
id: i,
text: `Row ${i} - ${'Lorem ipsum '.repeat(3)}`
}));
new VirtualScrollTable({
containerId: 'tableContainer',
data: testData,
rowHeight: 32,
viewportHeight: 400
});
| 優化點 | 說明 |
|---|---|
| DocumentFragment | 批量插入 DOM,減少 Reflow |
| 固定行高 | 避免計算每行高度,O(1) 定位;若行高不固定需預測量並緩存 |
| spacer margin-top | 只改變 margin 不改變 height,避免容器重排 |
| requestAnimationFrame | 滾動事件節流,配合 rAF 渲染 |
| 緩衝區 | visibleCount + 2,防止快速滾動出現空白 |
| 表頭 sticky | CSS position:sticky 替代雙表格同步滾動,簡潔高效 |
// 預測量所有行高(一次性),存入陣列
const rowHeights = data.map(item => estimateHeight(item)); // 或渲染隱藏行測量
const prefixSum = [0];
for (const h of rowHeights) prefixSum.push(prefixSum[prefixSum.length - 1] + h);
// 定位:二分查找 prefixSum 找到 startIndex
function findStartIndex(scrollTop) {
let lo = 0, hi = prefixSum.length - 1;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (prefixSum[mid] <= scrollTop) lo = mid + 1;
else hi = mid;
}
return Math.max(0, lo - 1);
}
虛擬滾動將「渲染複雜度」從 O(N) 降為 O(1),是大數據前端展示的標準解法。理解其核心:固定行高 + 占位撐高 + 可視區渲染 + 滾動同步,即可根據業務靈活實現或選型成熟庫。