What is Document Fragment in javascript and why to use it?


Document fragment is the document which is not the part of the active document tree or DOM.
If we want series of element to be appended to the active DOM then creating and inserting each element one by one requires some styling or other calculations.

Lets see with an example
var i = 0;
while (i < 100) {
    div.innerHTML += '<li>My list item = ' + i + '</li>';
i++; }

above statement always require some steps before the element is available in active DOM like
parse innerHTML
destroy existing child nodes of element
create child nodes
recompute styles which are defined in terms of parent child relationships
recompute physical dimensions of the page
etc so for every element these steps might take place which will be take time.

lets see one more example :

var i = 0; while (i < 200) {
    var e = document.createElement('li');
    e.innerText = 'list item = ' + i;
    div.appendChild(e);
i++; }

 this solution suffers from recalculation of styles, painting and layout everytime

better to use below solution :

var e;
var i = 0;
var fragment = document.createDocumentFragment();
 
while (i < 100) {
    e = document.createElement('li');
    e.innerText = 'list item = ' + i;
    fragment.appendChild(e);
i++; }
 
div.appendChild(fragment);

By using a document fragment all elements are added in fragment and then the fragment is appended to active DOM and all calculations are done at once like styling (like adapting to parent styles etc ) and other calculations

Comments

Popular Posts