DocumentFragments are useful when you want to create multiple DOM elements and add them to the DOM tree at once, as it is more efficient to do so using a DocumentFragment. This is because when you add elements to a DocumentFragment, they are not added directly to the DOM tree. Instead, they are added to the DocumentFragment’s own internal tree, and you can then add the entire fragment to the DOM tree at once using the appendChild
or insertBefore
methods. This can be more efficient than adding each element individually to the DOM tree, as it reduces the number of times the browser has to reflow and repaint the page.
Here is an example of how you might use a DocumentFragment to improve performance:
// create a DocumentFragment var fragment = document.createDocumentFragment(); // create some DOM elements var div1 = document.createElement("div"); var div2 = document.createElement("div"); var div3 = document.createElement("div"); // add the elements to the DocumentFragment fragment.appendChild(div1); fragment.appendChild(div2); fragment.appendChild(div3); // add the DocumentFragment to the DOM tree document.body.appendChild(fragment);
In this example, we create three div
elements and add them to a DocumentFragment. We then add the DocumentFragment to the body
element of the DOM tree, which adds all three div
elements to the body
at once. This is more efficient than adding each div
individually to the body
element.