views:

35

answers:

1

I am inserting elements into dom dynamically and for that i m using following steps :(jquery) The initial dom structure is as below:

<div parent div>
 </div>
 <div child div template>
</div>
  • clone the parent div using jquery .clone()
  • clone the child div and do manipulation
  • append to the cloned parent
  • do this for all child data
  • (parentdiv original).replaceAll(clonedparent)

Basically i want to clone the parent div in a manner so that it is available as a documentfragment and so that appending doesnt happen on the dom and gain performance .

Will jQuery clone() give the performance advantage by behaving like documentfragment? Or is there a better way to do this? I don't want to construct each child element as HTML string as the structure of them is pretty complex.

A: 

jQuery clone() does a plain DOM cloneNode(), except on IE, which inappropriately copies event listeners if you do that. To work around that, on IE jQuery does something utterly ghastly which really you don't want to know about. Which ain't fast.

replaceAll() is also not fast. It has to remove each child node from the DOM (which is particularly slow in jQuery because of its need to check data when removing something from the DOM) and add the new nodes one-by-one.

I don't really see what cloning gets you here really. Just do the manipulations directly on the children. If you've got a lot of manipulations to do and you're triggering relayouts that make it slow, you could temporarily hide the parent or detach it from the document, re-appending it when you're finished.

bobince
Thanks for the detailed answer. I am cloning child elements because i m creating new child elements on the fly and for that i m taking support of the template child element, cloning it and then appending. The children dont exist before hand, hence cant do manipulations by detach , what do I do in this case, i have to create new children using some kind of template..
ams
OK, clone-and-append the child, but you don't need to clone the parent as well. You can detach-and-reappend the parent, if you're sure you need to.
bobince
I hope cloning for many child elements is ok..is there any other way i can get ride of cloning for child elem?
ams