Last active
September 12, 2023 06:44
-
-
Save desinas/a86307ae75e5a3599864dd17ed228424 to your computer and use it in GitHub Desktop.
Add Page Content Efficiently - Performance - FrontENDev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fragment = document.createDocumentFragment(); // ← uses a DocumentFragment instead of a <div> | |
for (let i = 0; i < 200; i++) { | |
const newElement = document.createElement('p'); | |
newElement.innerText = 'This is paragraph number ' + i; | |
fragment.appendChild(newElement); | |
} | |
document.body.appendChild(fragment); // reflow and repaint here -- once! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The browser is constantly working to make the screen match the DOM. When we add a new element, the browser has to run through a reflow calculation (to determine the new screen layout) and then repaint the screen. This takes time. So, we have to create a extraneous div element just to hold all the p tags so we can add them all at once and then we append this div to the body element. So in the end, we have an extra div that isn't really needed. It was just around because we wanted to add each new p to it instead of to the body. We can use the
.createDocumentFragment()
method to create an empty DocumentFragment object.const myDocFrag = document.createDocumentFragment();