JavaScript Intermediate DOM & Async · 8 min read

DocumentFragment for Batch DOM Updates

Lesson 10 of 38 in the JavaScript learning path.

How do I insert many nodes without reflowing on every append?

Appending a node to a live list can force the browser to recalculate layout. Doing that once per lesson is wasteful when a catalog has dozens of rows. A DocumentFragment is a lightweight parent that is not on the page. You create elements, append them to the fragment, and then append the fragment to the real list. The children move into the list in one insertion, and the fragment itself does not appear as a DOM node you can see.

The sample builds the same twelve lessons two ways. The direct list calls append on the parent once per lesson. The fragment list calls append on the parent once. Both lists end with twelve children and the same labels, built with createElement and textContent. The difference is the number of parent insertions. That count is the reason to batch a catalog, a grade table, or any other loop that would otherwise touch the live document on every pass.

Syntax & Parameters

Syntax
const fragment = document.createDocumentFragment();
fragment.append(node);
parent.append(fragment);

Example

Interactive preview available
app.js
'use strict';

const lessons = [
  { title: 'Scope', minutes: 7 }, { title: 'Destructuring', minutes: 8 },
  { title: 'Arrays', minutes: 8 }, { title: 'getElementById', minutes: 6 },
  { title: 'querySelector', minutes: 6 }, { title: 'querySelectorAll', minutes: 7 },
  { title: 'textContent', minutes: 8 }, { title: 'classList', minutes: 6 },
  { title: 'createElement', minutes: 7 }, { title: 'DocumentFragment', minutes: 8 },
  { title: 'Click events', minutes: 6 }, { title: 'Delegation', minutes: 8 },
];

function lessonItem(lesson) {
  const item = document.createElement('li');
  item.textContent = `${lesson.title} (${lesson.minutes} min)`;
  return item;
}

function fillDirect(list) {
  list.replaceChildren();
  let appends = 0;
  for (const lesson of lessons) {
    list.append(lessonItem(lesson));
    appends += 1;
  }
  return appends;
}

function fillFragment(list) {
  list.replaceChildren();
  const fragment = document.createDocumentFragment();
  for (const lesson of lessons) {
    fragment.append(lessonItem(lesson));
  }
  list.append(fragment);
  return 1;
}

function render() {
  const direct = document.getElementById('direct-list');
  const batched = document.getElementById('fragment-list');
  const stat = document.getElementById('fragment-stat');
  if (direct === null || batched === null || stat === null) {
    console.log('missing lists');
    return;
  }
  const directAppends = fillDirect(direct);
  const fragmentAppends = fillFragment(batched);
  stat.textContent = [
    `items: ${lessons.length}`,
    `direct appends to the parent: ${directAppends}`,
    `fragment appends to the parent: ${fragmentAppends}`,
    `direct children: ${direct.childElementCount}`,
    `fragment children: ${batched.childElementCount}`,
  ].join('\n');
  console.log(stat.textContent);
}

const button = document.getElementById('build-catalog');
if (button !== null) {
  button.addEventListener('click', render);
}
render();

Expected Output

#fragment-stat and console:

items: 12
direct appends to the parent: 12
fragment appends to the parent: 1
direct children: 12
fragment children: 12

Each list shows Scope (7 min) through Delegation (8 min).

Line-by-Line Walkthrough

  1. lessons holds twelve plain objects. Two catalog lists will render the same data so the insertion counts can be compared.
  2. lessonItem creates an li and sets its textContent to the title and the minute count. No HTML string is involved.
  3. fillDirect clears the target, appends each item straight to that live parent, and returns how many appends it made.
  4. That return value is the length of the catalog, because each lesson touches the parent once.
  5. fillFragment clears its target, creates a DocumentFragment, and appends every item to the fragment instead of the list.
  6. One list.append(fragment) moves those children into the list. The function returns 1, the number of parent insertions.
  7. After that append, the fragment has no children left. They now belong to the list, so the fragment does not show up in the page.
  8. render bails out when any of the three nodes is missing, and otherwise runs both fillers.
  9. The status text records the item count, both append totals, and both child counts, then prints the same text.
  10. The build button runs render again, and the first call on load fills both lists immediately.

Common Pitfalls & Security

A fragment batches insertion. It does not make an HTML string safe. Nodes inside it should still be created with createElement and filled with textContent. Appending the fragment moves the nodes, so a second append of the same fragment adds nothing. Counting childElementCount on the fragment after the move shows zero, which surprises people who expected the fragment to keep a copy.

  • parent.innerHTML = html for a joined catalog parses markup. A title equal to the untrusted string <img src="x" alt="untrusted"> becomes an image and is an XSS hole.
  • Appending the fragment twice does not clone the rows. Create the nodes again, or clone them, for a second list.
  • The fragment is not an Element. It has no classList and it does not match querySelectorAll on the document before you append it.
  • replaceChildren at the start of each render drops old rows. That is intentional here, and it also drops listeners that were bound on those rows.
  • A fragment does not remove the cost of creating the nodes. It removes the repeated live-parent insertion.

Best Practices & Modern Standards

Build each row with a pure function, append those rows to a DocumentFragment, and append the fragment to the live parent once. Keep the source data in an array so a second render can rebuild from scratch. ES2024 does not replace DocumentFragment. It remains the standard way to batch DOM insertion without a library.

Measure with a counter of parent appends when you are learning, and with the performance timeline when a real catalog is slow. Do not switch back to an HTML string to save lines. The safe batch is still createElement, textContent, fragment, and one append. For a handful of nodes the direct loop is fine. Use the fragment when the loop is large enough that layout shows up.

Real-World Use

A course catalog dashboard draws every published lesson into a sidebar when the filter changes. Building twelve or two hundred rows directly on the live list makes the sidebar stutter. The widget creates the items on a fragment, appends that fragment once, and the child count matches the filtered array.

The same data can fill a comparison column the slow way during a lesson, so students see twelve parent appends next to one. Production code keeps only the fragment path. Titles stay in textContent, so a lesson name that contains a tag cannot change the sidebar structure.

Frequently Asked Questions

Does the fragment stay in the document?

No. Appending a fragment moves its children into the parent and leaves the fragment empty. Inspect the list and you see the li elements, not a fragment wrapper. Create a new fragment the next time you batch.

Why not append each li directly?

Each append to a live parent can force layout work. One append of a fragment does that work once. For a tiny list the difference is small. For a catalog redraw it is the point of the pattern.

Can I put text in the fragment with an HTML string?

You can, and you should not when any text is untrusted. Create elements and set textContent, then append those elements to the fragment. Batching does not remove the XSS hole in innerHTML.

Will querySelector find nodes while they are on the fragment?

A query from document will not see them yet, because the fragment is not in the document. You can call querySelector on the fragment itself before you insert it. After the append, query the live parent.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…