How to use DocumentFragment to render large lists faster

Using DocumentFragment does the trick because it isn't part of the active document tree structure. 

This means it doesn't interact with the main document until mounted. 

Hence, it doesn't impact the performance when changes occur to its contents. 

// Setup
const outlet = document.getElementById('#myList');
const fragment = new DocumentFragment();
const results = fetchResults(); // returns Array<Result>

We then go through each result and prepare it properly:

```, index) => {
    const li = document.createElement('li');
    li.textContent = result;
    // We append to the DocumentFragment

Finally, we append the end result to the list:


If we were to append each item to the list outlet within the ```map``` above, it would have triggered a repaint/reflow every time we performed the action.

Nick Ciolpan
26 Jul 2022
« Back to post