Why does cloneNode need to be used when appending a documentFragment?

后端 未结 4 1032
醉酒成梦
醉酒成梦 2021-01-04 22:36

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 th

4条回答
  •  鱼传尺愫
    2021-01-04 23:38

    I don't think it's necessary. I guess it only was used to detach the aElms from being statically referenced, where they would've need to be removed from their former parents when calling appendChild. It's only for performance in this test.

    However, the following code (more similar to the appendChild test) would make more sense to me:

    var oFrag = document.createDocumentFragment();
    for (var i = 0, imax = aElms.length; i < imax; i++)
        oFrag.appendChild(aElms[i].cloneNode(true));
    // using it here:             ^^^^^^^^^^^^^^^^
    o.appendChild(oFrag);
    

    Though it might be slower than calling it only once on the whole fragment, where the node tree is recursed with native code.

    Also check out http://jsperf.com/cloning-fragments :-)

提交回复
热议问题