The fastest way to repeatedly clone a set of nodes

I have curiosity with a plugin that I wrote for Knockout called knockout-fast-foreach , which is the fastest way to clone multiple nodes multiple times and inject them into the DOM.

Two things should happen in cloning: copying the nodes of the original template and pasting them back into the DOM .

Now there are some design options that include:

  • The source nodes will be children of the same DOM;
  • The target may have children not affected by the DOM injection, that is, not all child nodes may change;
  • The source can be <template>, <script>or a regular HTML DOM node.

So for example:

<template id='src'>ø</template>
<div id='target' data-bind='fastForEach: $data'>
</div>

When applying binding to the ko.applyBindings([1, 2, 3], document.getElementById('target'))result will be:

<template id='src'>ø <span data-bind='text: $data'></span></template>
<div id='target' data-bind='fastForEach: $data'>
  ø <span data-bind='text: $data'>1</span>
  ø <span data-bind='text: $data'>2</span>
  ø <span data-bind='text: $data'>3</span>
</div>

While this example is KO-specific, the performance of DOM manipulation should be a relatively universal characteristic.

As you can see from the linked source code above, the way I have come so far is to copy the source nodes into an array, then clone + paste them into the target at the desired position.

Is it possible that there is a faster way to clone and copy multiple elements (for example, possibly using document fragments)?

+4
source share
1 answer

. . , dom, dom - element.innerHTML = " html". , , . dom . . http://davidwalsh.name/css-js-animation.

+1

All Articles