Theory
Practice
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
Why and when use createDocumentFragment instead of createElement
ReplyDeleteGood information for developers. Now, they will know when to use createDocumentFragment...
Front End Development Services
best Front End Development Services Company
This comment has been removed by the author.
ReplyDelete