Skip to content Skip to sidebar Skip to footer

Fastest Dom Insertion

What are the best practices for doing DOM insertion? Is it faster to insert large chunks of html vs element at a time in a loop? Does it matter what html you are inserting, or onl

Solution 1:

Setting innerHTML is often faster than inserting seperate nodes.

Another possibility would be to create a DocumentFragment, which allows to insert the nodes all at once. Another advantage of using DocumentFragments is that they can easily be cloned, which can replace a lot of use cases for innerHTML and is potentially faster as no parsing is involved.

Solution 2:

innerHTML insertion is marginally faster than DOM manipulation 1:1 and gains more for cases where you're actually inserting multiple nodes and attributes etc.., but it's more error prone and dangerous given it's essentially an eval statement in disguise.

In my experience JS is so fast these days that the speed gains of innerHTML do not justify the risks for anything but the largest of insertions/iteration batches.

Long story short, you want to do the fewest DOM manipulations possible, so one tip when creating a hierarchy for insertion is to create them against each other in memory and then insert the highest element into the DOM at the last possible moment. That leaves the fewest render updates for the browser. Course again we're talking fractions of milliseconds...

Solution 3:

innerHTML is actually slower then direct DOM manipulation in many cases. check out this benchmark on jsperf

There is no "right answer", you will have to find the proper, most efficient method for your specific use case

Solution 4:

For large chunks of html, it is definitely faster to assign the text to innerHTML. Though it is supported by all the major browser, innerHTML is not in the w3c standard, so some programmer hesitate to use it.

Solution 5:

It's definitely faster to do it all at once. Also check out Steve Souder's blog and his book.

Post a Comment for "Fastest Dom Insertion"