Batch Updates
Batch Updates
Section titled “Batch Updates”Introduction
Section titled “Introduction”Each DOM manipulation triggers layout calculations. Batch updates using DocumentFragment minimize reflows for better performance.
The Problem
Section titled “The Problem”// ❌ Multiple reflows (slow)for (let i = 0; i < 1000; i++) { document.body.appendChild(document.createElement('div'));}// Each appendChild triggers a reflow — 1000 reflows!The Solution
Section titled “The Solution”// ✅ Single reflow (fast) — use DocumentFragmentconst fragment = document.createDocumentFragment();for (let i = 0; i < 1000; i++) { fragment.appendChild(document.createElement('div'));}document.body.appendChild(fragment); // One reflow onlyHow It Works
Section titled “How It Works”- Create a DocumentFragment (lightweight, not in DOM)
- Build your elements inside the fragment
- Append the fragment to the DOM (one operation)
- Fragment’s children are transferred, fragment itself is empty
Summary
Section titled “Summary”- Each DOM write can trigger a reflow (expensive)
- Batch reads together, batch writes together
- Use
DocumentFragmentfor bulk insertions - One append of the fragment = one reflow