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

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

    If you append a documentFragment to an element, and you later clear the appended nodes from that element, your documentFragment will also be empty and cannot be reused anymore! Appending a clone of your documentFragment prevents this and allows multiple reuses of your documentFragment.

    I assume the author of the jsperf snippet was testing for such a case.

    Example: dropdowns with a parent-child relationship. Lets say you have a dropdown where you select a continent, and a second dropdown that lists all the countries in that continent. If you want to cache the created documentFragments with the option nodes after creation, using cloneNode is necessary. Imagine someone selects europe, then africa, then europe again: you can either recreate the entire documentfragment, of cache it.

    I created a jsperf snippet to illustrate the performance difference of recreating the documentFragments vs caching and cloning the fragments:

    http://jsperf.com/documentfragment-cache-vs-recreate

提交回复
热议问题