DOM is fast

业界有一个普遍的观点, DOM is slow。的确,从经验上,频繁的 DOM 修改往往得到一个很慢的页面。但是事实是,DOM is fast, layout is slow。频繁的 DOM 修改也很容易频繁地触发 layout,拖慢了页面的速度。造成了 DOM is slow 的幻觉The short answer is that the DOM is not slow.

业界有一个普遍的观点, DOM is slow。

的确,从经验上,频繁的 DOM 修改往往得到一个很慢的页面。

但是事实是,DOM is fast, layout is slow。

频繁的 DOM 修改也很容易频繁地触发 layout,拖慢了页面的速度。造成了 DOM is slow 的幻觉

The short answer is that the DOM is not slow. Adding & removing a DOM node is a few pointer swaps, not much more than setting a property on the JS object.
However, layout is slow. When you touch the DOM in any way, you set a dirty bit on the whole tree that tells the browser it needs to figure out where everything goes again. When JS hands control back to the browser, it invokes its layout algorithm (or more technically, it invokes its CSS recalc algorithm, then layout, then repaint, then re-compositing) to redraw the screen. The layout algorithm is quite complex - read the CSS spec to understand some of the rules - and that means it often has to make non-local decisions.
Worse, layout is triggered synchronously by accessing certain properties. Among those are getComputedStyleValue(), getBoundingClientWidth(), .offsetWidth, .offsetHeight, etc, which makes them stupidly easy to run into. Full list is here (possibly a few years out of date):

https://news.ycombinator.com/item?id=9155564

关键字:JavaScript, dom, layout, the