Monday, June 23, 2014

Why and when use createDocumentFragment instead of createElement



In this post I will try explain you why you should learn about createDocumentFragment() and why you should use it.

Theory

document.createDocumentFragment() is method which create empty document fragment which is not part of main DOM tree. It's stored in memory and operations on it doesn't make changes in main document. By using them isntead of creating many new document elements we can get better page/application performance.

Practice

To prove this theory let's write some easy test. Let's say that we want get all texts from each a elements on page and write them on end of page. With standard method we can do this:

elemA = document.getElementsByTagName('a');
body = document.getElementsByTagName('body')[0];

for(var i = 0; i < elemA.length; i++){
  var span = document.createElement('span');
  span.textContent = elemA[i].textContent;
  body.appendChild(span);
}

Like you can see in each iteration we create new element and append it to the body. It's cause recalculation of DOM in each step. To prevent this we can create documentFragment and in each step append element to this fragment. Then, after the loop we append fragment to body.

Result will be the same but performance and time execution will be faster in second case. Here is example of second case:

elemA = document.getElementsByTagName('a');
body = document.getElementsByTagName('body')[0];
fragment = document.createDocumentFragment();

for(var i = 0; i < elemA.length; i++){
  var span = document.createElement('span');
  span.textContent = elemA[i].textContent;
  fragment.appendChild(span);
}
body.appendChild(fragment);


By using console.time() and console.timeEnd() methods we can check the execution time of both scripts. In my case it's 7ms for documentFragment and 43ms for loop with appending each time to body.

So like you can see createDocumentFragment() method is 6 times faster than standard method.

Gist for these tests you can find here: https://gist.github.com/lukasz-zak/48486ab35f7ea4bc1ba4

2 comments :

  1. Why and when use createDocumentFragment instead of createElement

    Good information for developers. Now, they will know when to use createDocumentFragment...

    Front End Development Services

    best Front End Development Services Company



    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete