We have seen these in previous chapters, but it is nice to touch upon them. Document fragments are reusable containers that we can create a DOM hierarchy in and attach all of those nodes at once. This leads to faster draw times and less repainting when utilized.
The following example showcases two ways of attaching a series of list elements utilizing straight-to-DOM addition and fragment addition:
const num = 10000;
const container = document.querySelector('#add');
for(let i = 0; i < num; i++) {
const temp = document.createElement('li');
temp.textContent = `item ${i}`;
container.appendChild(temp);
}
while(container.firstChild) {
container.removeChild(container.firstChild);
}
const fragment = document.createDocumentFragment();
for(let i = 0; i < num; i++) {
const temp = document.createElement('li');
temp.textContent = `item ${i}`;
fragment.appendChild(temp);
}
container.appendChild(fragment);
While the time between these two is tiny, the number of repaints that take place is not. In our first example, the document is going to repaint each time we add an element directly to it, whereas our second example is only going to repaint the DOM once. This is the nice thing about document fragments; it makes adding to the DOM simple, while also only utilizing minimal repaints.