Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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

like image 478
Khaleel Avatar asked Jan 10 '23 17:01

Khaleel


1 Answers

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.

like image 167
Martin Ernst Avatar answered Jan 12 '23 09:01

Martin Ernst