Reducing reflow using DocumentFragement

April 3rd, 2013 § 0 comments

This is a simple post which will demonstrate how you can reduce the reflow in browser and enhance the performance of the webpage. Before getting started with it lets look into what is reflow?

what is reflow?

According to Google,

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document.

So any actions, like adding an element to DOM, changing style or position of element etc may lead to reflow. Since this is really an expensive operation we have to reduce to get maximum performance.

Using DocumentFragement

Consider a case that you have a <ul> tag and you need to append 5 <li> tags into it.

var n=5;
var wrapper = document.getElementsByTagName("ul")[0];
while(n--){
    var inner = document.createElement('li');
    inner.innerHTML = "Inner" + n;
    wrapper.appendChild(inner);
}


Of course this code will works fine, But the issue is the appendChild is called in side loop, means 5 times it append a new element to DOM which leads to 5 reflow. Here is the rewrite for the same functionality.

var df = document.createDocumentFragment();
var n=5;
var wrapper = document.getElementsByTagName("ul")[0];
while(n--){
    var inner = document.createElement('li');
    inner.innerHTML = "Inner" + n;
    df.appendChild(inner);
}
wrapper.appendChild(df);


Here we Introduced a new element called DocmentFragment. According to Mozilla,

DocumentFragment is a minimal document object that has no parent. It is used as a light-weight version of document to store well-formed or potentially non-well-formed fragments of XML.

Since it is an Document object you can access it a like a node/container and call any document method, But since it doesn’t have a root node and not a part of DOM appending to documentFrament won’t trigger a reflow.

Thats where our second part gain importance, In that we create a documentFragment and append the <li> initially into it while in the loop. So the DocumentFragment can hold it like <ul> itself. Then We append the DocumentFragment to the <ul> in DOM, after exiting the loop, means the reflow will trigger only once even though we appended 5 <li> tags.

Now we reduced reflow to 1 instead of 5.

Thanks

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and http://blog.revathskumar.com - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube

Tagged , ,