使用 documentfragment 结合 requestanimationframe 进行分批处理。具体做法是先将所有 html 片段解析为 dom 节点,然后利用 requestanimationframe 将插入操作拆分为多个微任务或宏任务批次执行,每批处理一定数量的节点,从而避免单次长任务阻塞主线程。

如何将 HTML 字符串转换为可操作的 DOM 节点列表
通过 DOMParser 解析 HTML 字符串并提取子节点。创建一个空的 DocumentFragment,遍历解析后的文档片段,将每个子节点克隆到临时 Fragment 中,最终返回包含所有节点的数组,以便后续分批处理。

function parseHTMLToNodes(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const fragment = document.createDocumentFragment();
Array.from(doc.body.childNodes).forEach(node => {
fragment.appendChild(node.cloneNode(true));
});
return Array.from(fragment.childNodes);
}如何分批插入节点以避免长任务
使用 requestAnimationFrame 递归调用实现分批插入。设定每批处理的节点数量(如 50 个),在每帧中处理一批节点并将其追加到目标容器,直到所有节点处理完毕。这种方式确保 UI 渲染不被阻塞,保持页面响应性。
立即学习“Java免费学习笔记(深入)”;

function appendInBatches(nodes, container, batchSize = 50) {
let index = 0;
function processBatch() {
const end = Math.min(index + batchSize, nodes.length);
const fragment = document.createDocumentFragment();
for (let i = index; i < end; i++) {
fragment.appendChild(nodes[i]);
}
container.appendChild(fragment);
index = end;
if (index < nodes.length) {
requestAnimationFrame(processBatch);
}
}
requestAnimationFrame(processBatch);
}当输入 HTML 包含大量嵌套元素时如何处理
对于包含大量嵌套元素的 HTML 字符串,DOMParser 会一次性解析整个结构,生成完整的 DOM 树。此时 parseHTMLToNodes 返回的节点数组已包含所有层级节点,appendInBatches 按顺序插入即可。由于插入操作本身是同步的,但被拆分到多帧执行,因此即使节点嵌套深,也不会导致单帧任务过长。



















