[Django]-Javascript Create and Add div vs Clone, Modify and Add div

2👍

I agree that a JS templating engine might be the best solution.


As for performance, if you still want to do it on your own, regardless of whether you choose to clone or create, most important thing for doing that for 100 items in a loop is, don’t append each element to the document inside the loop, but use a DocumentFragment instead: Append the divs to the fragment, one after another, and after you are done with looping through your items append the fragment, that now contains all of those 100 items, to your document.

(A DocumentFragment is just a “soulless” temporary container – when you finally append the fragment to the document, it will just “dissolve” without leaving a trace, so the effect will be the same as if you had appended the 100 elements individually. As to why it improves performance, see https://stackoverflow.com/a/13771168/1427878.)

👤CBroe

2👍

In my current project I’m dynamically creating about 600 elements, each with about 10 nested children. They’re mostly identical aside from a text node and an src attribute of an image. The best pure-JS way I’ve found to create and modify these elements takes 10-15ms and works as follows:

  1. Create a DocumentFragment.
  2. Use the fragment to build a template.
  3. Deep clone the fragment.
  4. Modify the clone.
  5. Create the actual root element.
  6. Append the clone to the root element.

Repeat 3-6 as many times as necessary.

According to my tests on Chrome 66/Windows (https://jsperf.com/creating-multiple-nested-elements/1), this is about 10x faster than creating each element from scratch, and about 3x faster than using a non-DocumentFragment as the template root. I would imagine that the benefit becomes greater the more complex the structure you want to clone is.

👤Ophion

1👍

According to this, cloneNode is slightly better performance:
http://jsperf.com/clonenode-vs-createelement-performance/2

However, I really do suggest you take a look at something like KnockoutJS:
http://knockoutjs.com/examples/simpleList.html

It will save your sanity in the long run.

0👍

It’s faster to clone the div.

Check out this performance test.

Leave a comment