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.)
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:
- Create a DocumentFragment.
- Use the fragment to build a template.
- Deep clone the fragment.
- Modify the clone.
- Create the actual root element.
- 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.
- [Django]-Django no module named setting
- [Django]-Pagination doesn't accept dict as data – unhashable type
- [Django]-Django: object needs to have a value for field "…" before this many-to-many relationship can be used
- [Django]-Uploading image in django: getting "global name context is not defined" error
- [Django]-Django .."join" query?
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.
- [Django]-Any clue on this error with generic relation using Django Orm?
- [Django]-Django1.4.0:ImportError: No module named base