I’ve been looking at using documentFragments in a Backbone.js app and was wondering why I see examples where “cloneNode” is used when appending the documentFragment to the parent DOM element.
An example can be seen here. If you look down at the DocumentFragment section you’ll see this:
oFrag = document.createDocumentFragment();
for (var i = 0, imax = aElms.length; i < imax; i++) {
oFrag.appendChild(aElms[i]);
}
o.innerHTML = '';
o.appendChild(oFrag.cloneNode(true));
Why does “oFrag” get cloned instead of just appending it? Another blog post doesn’t use “cloneNode” (as a comparison).
Your first link refers to the blog post where the autor uses
document.getElementsByTagNameinstead ofdocument.getElementById, like in test case. If you want a multiple elements (namely: divs) to be given the samedocumentFragment, you must clone it:via MDN
Most likely the author (or someone else) copy-pasted the code without taking this into consideration. Try it yourself – you can use
appendChildwithoutcloneNodeand everything works fine.Another possibility is that someone who created this test case on jsperf didn’t get much how preparation code works and was worried that the very first test will empty
aElmsarray and it won’t work anymore. In fact preparation code is executed before each timed iteration, so there’s no need to be worried about its contents.The last thing may the performance concern. If you really want to test the real insertion, you need to clone the node. Otherwise, you’ll test tree reattachment instead (see MDN link above).
Also please note that cloning destroys event listeners.
Happy fragmentin’! 😉