I have a curiosity with a plugin I have written for Knockout, called knockout-fast-foreach, namely what is the fastest way to repeatedly clone a set of nodes and inject them into the DOM.
There are two things that need to happen in the cloning, namely copying out the source template nodes, and injecting them back into the DOM.
Now there are some design choices that apply, that include:
- The source nodes will be children of a single DOM entity;
- The target may have siblings unaffected by the DOM injection i.e. not all the child nodes may change;
- The source may be a
<template>
,<script>
or regular HTML DOM node.
So for example:
<template id='src'>ø</template>
<div id='target' data-bind='fastForEach: $data'>
</div>
When one applies the binding with ko.applyBindings([1, 2, 3], document.getElementById('target'))
the 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 that example is KO-specific, the performance of the DOM manipulation ought to be a relatively universal characteristic.
As you can see from the linked source code above, the way I have come up with so far is to copy the source nodes into an array, then clone + inject them into the target at the desired position.
Is is possible there is a faster way to clone and copy multiple elements (e.g. perhaps using document fragments)?