Document Fragments

Thursday 24 June, 2010 by moschel

Document Fragments kick ass for performance.  Just ask John Resig.  The following is code I used to convert a table's table-layout property from auto to fixed:

var tbody = this.scrollable.cache.tbody,
    table = this.scrollable.cache.table,
    tr = tbody.children(":first"),
    children = tr.children(),
    fragment = document.createDocumentFragment(); 

// go through the tds and create col elements in the fragment
for(var i =0; i< children.length-1; i++){
    fragment.appendChild( 
        $("<code>").width(children.eq(i).outerWidth())[0] 
    );
}
//add the fragment to the top of the table
table.prepend(fragment)

//convert fixed
table.css("tableLayout","fixed")

I was hoping that something like $(document.createDocumentFragment()).append() would work, but no such luck.  I'll probably submit a patch.

Using document fragments made the conversion to a fixed layout pretty much instantaneous.  Hopefully you'll find this trick useful.

Related Content