Khaleel
Khaleel

Reputation: 1371

"document.createElement" Performance

I wanted to create numerous rows in a popup to show my data using for loop, I was using text string to create and append the div , However I found document.createElement is performant and used that which increased the performance 20%, but since I populate 1000s of rows the time taken to create element by document.createElement is very high. Is there any way to improve performance by creating element once and resuse it with numerous instance, any advice on this would be appreciated

Upvotes: 7

Views: 6674

Answers (1)

Martin Ernst
Martin Ernst

Reputation: 3279

Once you have created an element, you can use Element.cloneNode() to copy it. It takes same time as document.createElement(), but has one advantage: if you have set several attributes or childNodes/innerHTML on the element, you can copy those too with one call: Element.cloneNode(true).

Most time takes the DOM-insertion of newly created Elements, and therefor insertion of every single new element is slow. A faster way is to create a documentFragment, append all new elements to that in the structure you need and then add the complete fragment to the DOM.

Upvotes: 14

Related Questions