DocumentFragment Batches Node Insertions
Assemble rows on a detached fragment and attach once, so the document sees a single insertion; the fragment itself never enters the tree.
Code
const rows = [
{ id: 'a1', label: 'Alpha' },
{ id: 'b2', label: 'Beta' },
{ id: 'c3', label: 'Gamma' },
];
// 逐条 append:每条都触发一次真实插入
const eager = document.createElement('ul');
for (const row of rows) {
const li = document.createElement('li');
li.dataset.id = row.id;
li.textContent = row.label;
eager.append(li);
}
// 先在游离 fragment 上拼好整棵子树,再一次搬进文档:只插入一次
const fragment = document.createDocumentFragment();
for (const row of rows) {
const li = document.createElement('li');
li.dataset.id = row.id;
li.textContent = row.label;
fragment.append(li);
}
console.log('fragment parent before attach:', fragment.parentElement);
const lazy = document.createElement('ul');
lazy.append(fragment); // fragment 自身不入树,子节点整体移交
console.log('fragment children after attach:', fragment.childNodes.length);
console.log('list items:', lazy.children.length);
console.log('first item:', lazy.firstElementChild.textContent);Two insertion strategies
The eager list appends each li directly, triggering a real insertion per row. The lazy variant builds the same rows on a detached DocumentFragment and appends the fragment once — the document sees a single insertion.
Fragment lifecycle
Before attaching, fragment.parentElement is null (it has no parent). After lazy.append(fragment), the fragment itself never enters the tree: fragment.childNodes.length is 0 because its children were handed over to the ul, which reports list items: 3 and first item: Alpha.
Where this applies
Rendering batches of rows into a live container benefits from the single-insertion path; the fragment is also reusable in the sense that its children move out wholesale.
Interactive Tools for This Topic
FAQ
- Does the fragment itself end up in the DOM?
- No. Appending a fragment moves its children into the target and leaves the empty fragment out of the tree, which is why fragment.childNodes.length reads 0 afterwards.
- Why build rows on a fragment instead of the live list?
- The live list then observes a single insertion instead of one per row, avoiding repeated layout-affecting mutations during assembly.
Report a problem with this exampleOpens a pre-filled issue on GitHub.