语法节
let fragment = document.createDocumentFragment();
fragment是一个指向空DocumentFragment
对象的引用。
DocumentFragments
是DOM节点。它们不是主DOM树的一部分。通常的用例是创建文档片段,将元素附加到文档片段,然后将文档片段附加到DOM树。在DOM树中,文档片段被其所有的子元素所代替。
因为文档片段存在于内存中,并不在DOM树中,所以将子元素插入到文档片段时不会引起页面回流(对元素位置和几何上的计算)。因此,使用文档片段通常会带来更好的性能。
示例
setTimeout(() => {
// 插入十万条数据
const total = 100000
// 一次插入 * 条,如果觉得性能不好就减少
const once = 200
// 渲染数据总共需要几次
const loopCount = total / once
let countOfRender = 0
let ul = document.querySelector("ul");
function add() {
// 优化性能,插入不会造成回流
const fragment = document.createDocumentFragment();
for (let i = 0; i < once; i++) {
const li = document.createElement("li");
// li.innerText = Math.floor(Math.random() * total);
li.innerText = `这里是第 ${countOfRender} 次的 li ${i}`;
fragment.appendChild(li);
}
ul.appendChild(fragment);
countOfRender += 1;
loop();
}
function loop() {
if (countOfRender < loopCount) {
window.requestAnimationFrame(add);
}
}
loop();
}, 0);
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createDocumentFragment