tags:

views:

448

answers:

4

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 only how big the chunk is?
  • It it faster to insert a table, vs inserting just the rows using the table hack?

Thanks

+1  A: 

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.

Maurice Perry
+6  A: 

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...

annakata
i am inserting a 500kb block of rows. and its taking about 750ms which is notacable
mkoryak
500k! A). this doesn't sound like JS is the right tool for the job B). you can't packet this into page chunks? C). unroll the loop as much as you can and go with innerHTML, that'll give you your lower boundary
annakata
+1  A: 

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

Hank Gay
+8  A: 

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.

Christoph
Upvoted for DocumentFragment. It's not quite as fast as innerHTML across the board, but can be faster in real world cases (assuming lots of concat), and is generally a lot cleaner/better code.
eyelidlessness