DOM creation and manipulation tips and tricks

In this post, I would like to share a simple DOM creation and manipulation technique which will provide some performance boost.

The goal of this post is to improve browser DOM manipulation performance by reducing unwanted reflow and repaint process. If you are unaware of them you should go through the below topic before getting started with this post.

Reflow and repaint

Use Document fragment
This is an already known technique. Using document fragment allow the separation of DOM creation from live document so that it will avoid unnecessary browser reflow and repaint.

var fragment= document.createDocumentFragment();

Clone nodes
Cloning already created element using cloneNode. This will be helpful when creating large number of same element. Mostly likely it can be used while creating table tr elements from JSON.

var fragment= document.createDocumentFragment();
var div = document.createElement("div");

Batch DOM update
Always batch the DOM update. Batch the DOM changes will reduce browser reflow and repaint.

Using requestAnimationFrame for DOM changes
This technique will provide a considerable performance when changing the live document. requestAnimationFrame will be used to update the DOM changes when the next reflow/repaint happens.
Normally it is introduced to do smooth animation experience in browser but here we can use this to do a single DOM update.

  document.body.appendChild( document.createElement("div") );

Use insertAdjacentHTML instead of innerHTML
This will be used when we need to append dynamic content to the same element.
We can use the innerHTML as follows.

var div = document.createElement("div");
div.innerHTML ="Hi" //<div>Hi</div>

div.innerHTML += " Dude"; //<div>Hi Dude</div>

But the above one have significant performance impact as it needs to re-parse all the child element already present.
To overcome this we can use insertAdjacentHTML which will append the inner HTML without touching the other elements. It only parses the new HTML need to be appended.

var div = document.createElement(&quot;div&quot;);
div.innerHTML = "Hi";  //<div>Hi</div>

div.insertAdjacentHTML("afterend", " Dude"); //<div>Hi Dude</div>

Following the above methods will provide a better performance in most of the modern browsers.

Happy scripting….


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s