Reputation: 3026
AFAIK, the benefit of document fragments is that they don't cause reflow events, until the fragment is inserted into the DOM. Sounds reasonable, but it seems that out-of-DOM elements don't cause reflows either.
For example:
// with document fragment
var df = document.createDocumentFragment();
// append a bunch of hyperlinks to df
var container = document.createElement('div');
container.appendChild(df);
document.body.appendChild(container);
// with in-memory element
var container = document.createElement('div');
// append a bunch of hyperlinks to container
document.body.appendChild(container);
I ran this in Chrome and Firefox, and didn't see any performance differences between the two versions.
Given the age of the createDocumentFragment
method (even IE6 supports it), my theory is that it was more efficient at some point, but years of optimizations to browser rendering engines have made it unnecessary. Is this correct?
Upvotes: 3
Views: 2421
Reputation: 339816
A normal DOM insertion can only insert one node (and by extension its children, and their children, etc) all in one go.
A document fragment can contain multiple "top level" nodes which can all be added in one go, without requiring that they already share a common parent before they're added to the DOM.
In your example it doesn't matter, because you have that single container
div which is the parent of all the child nodes, so "normal" DOM insertion works fine.
Upvotes: 2
Reputation: 1793
Performance matters. createDocumentFragment is out-of-dom element. Operations with it are performed faster. So if you have to actively manipulate with fragmemt before appending to the DOM - use createDocumentFragment.
Otherwise - no differense.
Upvotes: 1
Reputation: 3815
Fragments are for use when you have many elements to append to an existing element. When you just have a single element to append (along with it's children), I don't believe their is any performance difference - but if you're forced to append many to the same target, a fragment may be appropriate. John Resig set up a test for this a while back, which you can run here - by all appearances, fragments still come through with better performance in the right circumstances.
His full post on the subject can be found here, which provides a pretty decent overview of the different performance characteristics.
Upvotes: 4