JAVASCRIPT

Efficient Bulk DOM Insertion with DocumentFragment

Optimize performance when adding many new elements to the DOM by using a DocumentFragment. This reduces reflows and repaints, improving UI responsiveness.

function addItemsEfficiently(containerSelector, itemsArray) {
    const container = document.querySelector(containerSelector);
    if (!container) {
        console.error("Container element not found:", containerSelector);
        return;
    }

    const fragment = document.createDocumentFragment();

    itemsArray.forEach(item => {
        const li = document.createElement('li');
        li.className = 'list-item';
        li.textContent = item.text;
        // Optionally add other attributes or children
        // const btn = document.createElement('button');
        // btn.textContent = 'Click';
        // li.appendChild(btn);
        fragment.appendChild(li);
    });

    container.appendChild(fragment);
}

// Example Usage:
// const data = [
//     { text: 'Item One' },
//     { text: 'Item Two' },
//     { text: 'Item Three' },
//     { text: 'Item Four' },
//     { text: 'Item Five' }
// ];
//
// // Assuming there's a <ul id="myList"> in the HTML
// addItemsEfficiently('#myList', data);
How it works: This snippet demonstrates using `DocumentFragment` to efficiently add a large number of elements to the DOM. Instead of appending each element individually to the live DOM (which can cause multiple reflows and repaints), elements are first appended to an in-memory `DocumentFragment`. Once all elements are added to the fragment, the fragment itself is appended to the live DOM in a single operation, significantly 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