JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network
Q&A Logo

How can I improve the performance of my JavaScript code when updating the DOM frequently?

Asked on Oct 09, 2025

Answer

To improve the performance of your JavaScript code when updating the DOM frequently, consider using techniques like batching DOM updates and minimizing reflows. Here's a simple example using `DocumentFragment` to batch updates:
<!-- BEGIN COPY / PASTE -->
        const fragment = document.createDocumentFragment();
        for (let i = 0; i < 100; i++) {
            const newElement = document.createElement('div');
            newElement.textContent = `Item ${i}`;
            fragment.appendChild(newElement);
        }
        document.getElementById('container').appendChild(fragment);
        <!-- END COPY / PASTE -->
Additional Comment:
  • Use "DocumentFragment" to batch DOM updates, which reduces the number of reflows and repaints.
  • Create elements and append them to the fragment first, then append the fragment to the DOM.
  • This approach is more efficient than appending each element directly to the DOM one by one.
✅ Answered with JavaScript best practices.
← Back to All Questions