If you are writing an application/page that does a large amount of DOM manipulation, using document.createDocumentFragment() can dramatically increase performance of your application/page. Per David Walsh, a senior web developer with Mozilla:
DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node. Doing so allows developers to produce structure without doing so within the visible DOM -- an increase of speed is the true advantage.Conceptually, both work in a similar fashion, but as Walsh points out, createDocumentFragment is more like a virtual DOM, which you can modify without the cost of restyling/redrawing a page. You do all of the same manipulation as with createElement, but you just append everything to the DOM in one fell swoop, as opposed to many appendChild calls.
DOM injections and modifications are taxing, so the fewer the interactions the better; that's where the DocumentFragment comes in... Using DocumentFragments is faster than repeated single DOM node injection and allows developers to perform DOM node operations (like adding events) on new elements instead of mass-injection via innerHTML.
Because the end result will look the same, we'll simply take a look at code examples of each method. In this case, let's prentend we need to add four rows to an existing table.
Items | Unit Cost | Quantity | Total |
---|---|---|---|
widget A | $20.00 | 3 | $60.00 |
widget B | $15.00 | 4 | $60.00 |
See the code in the JS tab. The first function, addRowsByElement(), adds the rows using createElement. You cannot see it until the elements are finally added to the list (poList element) in the last line of the function, but this function is manipulating the DOM behind the scenes. Now, for this amount DOM manipulation, there will likely not be a lot of calculation savings, but when scaling this up the function becomes inefficient.
The next function looks nearly identical; however, we are using createDocumentFragment() to handle all of the manipulation through a virtual DOM. So, we create the row and cells, just as in the previous function, but we append them to the fragment. Once we are done with the loop, we append the fragment to the DOM, which is more efficient.
So, the general rule of thumb is: if you are just doing a few DOM manipulations, createElement() is fine; however, if you do a lot of DOM manipulation, or if the application/page will be heavily used, it makes more sense to use createDocumentFragment().