Dojo FAQ: When should I use DocumentFragments?

By on July 23, 2014 11:36 am


A common practice when adding new elements to a document is to add them to a container DIV and then insert that node into into a document. A lesser used alternative is the DocumentFragment class. So, what is a document fragment, and when should you use one instead of a container DIV?

The main reason to use a container DIV is performance efficiency. Adding elements to a DOM document causes a relatively expensive document reflow, while adding elements to an external node and then inserting that into the document only causes a single reflow. There are times, however, when using a container DIV is problematic. For example, assume you need to add 1000 table rows to an existing TBODY element. Using a container node would result in an invalid document since there is no element that can contain TR elements in a TBODY. However, you can use a document fragment to efficiently handle this use case.

A document fragment is a lightweight container that looks and acts like a standard DOM node, with the key difference that when a document fragment is added to a document, the children of the fragment are added in its place. This operation is still treated as a single node insertion, in that the document is only reflowed after all the children have been added, so inserting a fragment is generally as efficient as inserting a single node. In the case of our table example, the new TR elements can be added to a DocumentFragment, and then the fragment can be appended to the TBODY. The result will be that all the TR elements in the fragment are appended directly to the TBODY.

DocumentFragments are nothing new; they are supported as far back as Internet Explorer 6. Dojo’s dom-construct.toDom function (and the dojo._toDom function before that), which converts HTML strings into DOM nodes, has always returned the new nodes in a DocumentFragment. So, to answer the original question, you can use a fragment anywhere you don’t need the structure provided by a container node, and you should use a document fragment in situations where a container node is unsuitable.

Learning more

SitePen covers DocumentFragments and other DOM manipulation topics in our Dojo workshops offered throughout the US, Canada, and Europe, or at your location. We also provide expert JavaScript and Dojo support and development services. Contact us for a free 30 minute consultation to discuss how we can help.