How to render multiple DOM nodes efficiently?

Tino
2 min readMar 17, 2021

Hello folks, this is short post so by the time you finish your cup of tea, you will know how to efficiently render a bunch of nodes on the screen without causing much refresh of flickering unicorns on your screen.

Let’s get going. First, let me introduce you to the a special node that is a document fragment. A document fragment is like an invisible shopping bag that you can use to collect nodes you wanna put on the screen at a later time. So, to create one, all you need to do is:

const docFrag = document.createDocumentFragment();

Now that we’ve got a bag, let’s fill it with some dummy nodes for the sake of this exercise. Let’s generate 1000 nodes and add them to our bag. In real life probably you will have some search results or shopping bag items as part of a response from the server.

const myNode;for (let i = 0; i < 1000; i++) {  // create a new node  myNode = document.createElement('div');  // put some dummy data inside the node  myNode.innerText = 'Helicopter '+ i;  // add the node into the bag  docFrag.appendChild(myNode);}

Now, let’s say you have a container node on the page where you want to display all these nodes.

const myContainer = document.querySelector('#container');myContainer.appendChild(docFrag);

Voila! Wasn’t that hard was it? Not only this method of adding multiple nodes is efficient but it’s also quite easy to comprehend.

Enjoy!

Tino

--

--

Tino

Software Developer and Helicopter pilot. Inventor of bubbology.