JAVASCRIPT

Batch DOM Updates Using Document Fragments for Performance

Optimize JavaScript DOM manipulations by grouping multiple element additions or updates within a DocumentFragment, significantly reducing reflows and repaints for better performance.

function updateElementsWithFragment(parentId, dataArray) {
    const parent = document.getElementById(parentId);
    if (!parent) {
        console.error(`Parent element with ID '${parentId}' not found.`);
        return;
    }

    // Create a document fragment
    const fragment = document.createDocumentFragment();

    // Populate the fragment with new elements
    dataArray.forEach(item => {
        const li = document.createElement('li');
        li.textContent = item.name;
        fragment.appendChild(li);
    });

    // Clear existing children (optional, depending on desired behavior)
    // parent.innerHTML = ''; 

    // Append the fragment to the DOM once
    parent.appendChild(fragment);
}

// Example Usage:
// Assume an HTML structure: <ul id="myList"></ul>
// const items = [{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }];
// updateElementsWithFragment('myList', items);
How it works: This snippet demonstrates how to use a `DocumentFragment` to perform multiple DOM manipulations efficiently. Instead of appending elements one by one directly to the main DOM (which can trigger costly reflows and repaints), elements are first added to the lightweight fragment, and then the entire fragment is appended to the DOM in a single operation, improving performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs