DOM Performance

Batch DOM Updates

Example

Each DOM change can trigger style and layout work. Build elements off-screen in a DocumentFragment and insert them once:

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<ul id="list"></ul>
<p id="info"></p>
<script>
  const t = performance.now();
  const frag = document.createDocumentFragment();
  for (let i = 1; i <= 1000; i++) {
    const li = document.createElement("li");
    li.textContent = "Item " + i;
    frag.append(li);
  }
  document.getElementById("list").append(frag);   // one insertion
  document.getElementById("info").textContent = "1000 items rendered in " + (performance.now() - t).toFixed(1) + " ms";
  document.getElementById("list").style.cssText = "height:60px;overflow:auto";
</script>

</body>
</html>

Result

Avoid Layout Thrashing

// slow: read, write, read, write... forces layout on every iteration
for (const el of items) {
  el.style.width = el.parentElement.offsetWidth / 2 + "px";
}

// fast: read everything first, then write everything
const widths = items.map((el) => el.parentElement.offsetWidth);
items.forEach((el, i) => (el.style.width = widths[i] / 2 + "px"));
  • Use event delegation instead of thousands of listeners.
  • Debounce/throttle scroll, resize and input handlers.
  • Use requestAnimationFrame for visual updates.
  • Render long lists virtually (only the visible rows).