Skip to content

Instantly share code, notes, and snippets.

@desinas
Last active September 12, 2023 06:44
Show Gist options
  • Save desinas/a86307ae75e5a3599864dd17ed228424 to your computer and use it in GitHub Desktop.
Save desinas/a86307ae75e5a3599864dd17ed228424 to your computer and use it in GitHub Desktop.
Add Page Content Efficiently - Performance - FrontENDev
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!
@desinas
Copy link
Author

desinas commented Apr 9, 2018

Using A Loop To Add Content

This code does this two hundred times:

  • creates a paragraph element
  • adds some text to the paragraph
  • adds the paragraph to the page

@desinas
Copy link
Author

desinas commented Apr 9, 2018

There are quite a few things we could do to improve this code:

  • create some parent container element outside of the loop
  • append all new paragraph elements to this parent container
  • append this parent container to the body element instead of appending each time through the loop

@desinas
Copy link
Author

desinas commented Apr 9, 2018

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();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment