Skip to content

怎么在文档中渲染大量的数据,如100万条数据万条数据

核心思路:使用createDocumentFragment创建Dom片段 和 requestAnimationFrame来分批渲染数据。

js

function renderLargeData(data) {
    const container = document.getElementById('data-container');
    const fragment = document.createDocumentFragment();
    let index = 0;
    const batchSize = 1000; // 每次渲染1000条数据

    function renderBatch() {
        const end = Math.min(index + batchSize, data.length);
        for (; index < end; index++) {
            const item = document.createElement('div');
            item.textContent = `数据项 ${data[index]}`;
            fragment.appendChild(item);
        }
        container.appendChild(fragment);

        if (index < data.length) {
            requestAnimationFrame(renderBatch); // 继续渲染下一批
        }
    }

    renderBatch();
}