Fastest DOM insertion

后端 未结 5 637
花落未央
花落未央 2020-12-08 22:43

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 h
5条回答
  •  生来不讨喜
    2020-12-08 23:06

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

提交回复
热议问题