Javascript Document Fragments

Originally published at WillWorkForBanjos.com

Most new front-end developers only experience Javascript through one of many popular Javascript frameworks such as MooTools or jQuery. That's not necessarily a bad thing but it does limit them in certain ways. People using jQuery to learn programming and front-end development may not realize that jQuery is really just an interface to more complex raw Javascript. While jQuery is extremely helpful and a tool I rarely go without when working on the front-end, there are still some things that are better done using raw Javascript. One of the areas that jQuery really excels at is simplifying DOM interactions. For instance if I wanted to change the contents of my body tag I could just do this:

$("body").html('new content');

However, let's say you've got an application that needs to have a dynamic front-end. You want several areas of your page to be changeable either through AJAX requests or user-interactions within the page. Using jQuery's html() and append() functions in this situation will negatively affect performance (potentially up to 60%). The answer is to manually utilize the same thing that jQuery is using: Document Fragments. Document Fragments are just lightweight containers made to hold DOM nodes and you interact with them via included functions such as setAttribute(). Let's look at a simple example where we insert a short list to the page using both jQuery and Document Fragments.

jQuery:
$("#content").append('<ul><li>Item</li></ul>');

Javascript:
var fragment = document.createDocumentFragment();
var list = document.createElement('ul');
var item = document.createElement('li');
item.innerHTML = 'Item';
list.appendChild(item);
fragment.appendChild(list);
document.getElementById('content').appendChild(fragment);

As you can see there are some trade-offs. Using raw Javascript is a more verbose process and in simple cases doesn't merit being used over jQuery. However, when you need to interact with the DOM quite a bit or quite often it can make a world of difference in performance. For the performance minded/curious, there is actually an online performance test that has been revised and updated many times over the past couple of years that looks at this exact comparison. The current revision (41) can be seen at jsperf.com.

comments powered by Disqus