Tiffany B. Brown

30 November 2012

Make fewer DOM updates with createDocumentFragment()

During a recent conversation about some code I've released, the other party asked me why I didn't use a document fragment. I think my reaction was more or less "What, well, um, I don't know, so I'm just going to bullshit and pretend I know what you're talking about or something."

I'm not one to be caught looking stupid twice, so I promptly did some Google-ing, and learned about the document.createDocumentFragment() method.

How. Did I. Not. Know. About. This. Already? This method improves your JS performance by creating a container of sorts. You can append the container and then add it to the DOM in one operation instead of several. As we know, DOM operations are expensive. Reducing the number is a great way to make your scripts more efficient.

The code in question created several objects and added them to the DOM one-by-one.

var fruits = ['apple','orange','banana','mangosteen','pineapple'],
    ol = document.getElementById('thelist');

fruits.map( function( o ){
    var li  = document.createElement('li');
    li.textContent = o;
    ol.appendChild( li );
});

This works of course, but it updates the DOM multiple times — a great way to slow down UI performance. Let's improve its efficiency by using document.createDocumentFragment().

var fruits = ['apple','orange','banana','mangosteen','pineapple'],
    ol,
    df = document.createDocumentFragment();

fruits.map( function( o ){
    var li  = document.createElement('li');
    li.textContent = o;
    df.appendChild( li );
});

ol = document.getElementById('thelist');
ol.appendChild( df );

There's a little more JavaScript involved, but now it's updating the DOM tree once. You can see how each stacks up speed-wise in this performance test.