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

后端 未结 4 1031
醉酒成梦
醉酒成梦 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:24

    Your first link refers to the blog post where the autor uses document.getElementsByTagName instead of document.getElementById, like in test case. If you want a multiple elements (namely: divs) to be given the same documentFragment, you must clone it:

    If child is a reference to an existing node in the document, appendChild moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).

    This also means that a node can't be in two points of the document simultaneously. So if the node already has a parent, it is first removed, then appended at the new position.

    via MDN

    Most likely the author (or someone else) copy-pasted the code without taking this into consideration. Try it yourself - you can use appendChild without cloneNode and 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 aElms array 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'! ;)

提交回复
热议问题