JavaScript 中动态设置多个 CSS 样式以应用于节点的最有效方法是什么?

What is the most efficient way in JavaScript to dynamically set multiple CSS styles so it applies to a node?

我有一些代码,我需要在单个 DOM 元素上设置多个样式,我担心如果样式数量变大,它不会有好的性能,因为它必须访问dom 节点每次。有没有更好的方法来处理这个问题?

这是我目前所拥有的(功能有效,是我能想到的最有效的方式)。

const rootStyle = document.documentElement.style,
      cssVars = getCssVars();
for (var key in cssVars) { // eslint-disable-line no-restricted-syntax
    rootStyle.setProperty(key, cssVars[key]);
}

像 "What is the fastest/efficient way to ..." 这样的问题只能针对特定版本的浏览器进行真正的回答,而不是一般的。浏览器供应商不断针对各种事物优化他们的浏览器。

在这种情况下可以安全地假设,大多数主要浏览器都了解您在这里做什么,并等到您完成后再呈现结果。

这里摘自 Google 对“pixel pipeline”的描述,让您了解发生了什么:

  1. JS / CSS > Style > Layout > Paint > Composite The full pixel pipeline

If you change a “layout” property, so that’s one that changes an element’s geometry, like its width, height, or its position with left or top, the browser will have to check all the other elements and “reflow” the page. Any affected areas will need to be repainted, and the final painted elements will need to be composited back together.

  1. JS / CSS > Style > Paint > Composite The pixel pipeline without layout.

If you changed a “paint only” property, like a background image, text color, or shadows, in other words one that does not affect the layout of the page, then the browser skips layout, but it will still do paint.

  1. JS / CSS > Style > Composite The pixel pipeline without layout or paint.

If you change a property that requires neither layout nor paint, and the browser jumps to just do compositing.

This final version is the cheapest and most desirable for high pressure points in an app's lifecycle, like animations or scrolling.

因此,如果您遇到性能问题,您可以尝试避免更改 css 触发 "reflow"。您的 for-loop 可能不是瓶颈,但许多浏览器提供了分析工具,可让您测试代码某些部分的性能。