4

For quite a while, I've taken this warning very seriously:

Scoped styles do not eliminate the need for classes. Due to the way browsers render various CSS selectors, p { color: red } will be many times slower when scoped (i.e. when combined with an attribute selector). If you use classes or ids instead, such as in .example { color: red }, then you virtually eliminate that performance hit.

In fact, I'll often go to great lengths to use only class selectors (e.g. adding a "last" class instead of using :last-child).

I'm unclear how important this actually is. Specifically, I have two questions:

  1. Is the render performance hit isolated to the component? In other words, does scoping a ul, which then adds ul[data-v-f3f3eg9] to the CSS, going to globally punish all ul renders?
  2. If I nest the element selector inside of a class, does that help in any way? E.g. using .messages p:last-child instead of p:last-child?

NOTE

I also notice this is in the Vue Style Guide here, which I trust to be more recently updated. Again it uses vague terms like "will be considerably slower", so I'm not sure what to make of that.

tony19
  • 125,647
  • 18
  • 229
  • 307
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • I don't use Vue nor scoped CSS, but I assume the Vue developers are smart and have implemented the mechanism correctly and optimized it. Because it is (assumably) some kind of pre-processing mechanism, it will add to page loading time. This 2014 [SO answer](https://stackoverflow.com/a/22284323/2015909) says (indirectly) that there would be no punishment for using attribute selectors. Makes me wonder how old the warning is you are referencing (the page has no date attached). However, should this be a runtime mechanism (to me, too silly to even consider) it will degrade overall performance. – Rene van der Lende Aug 12 '20 at 14:03
  • The answer to your 2nd question is almost certainly no. You still have the performance hit of scoping, just after a faster lookup like a class selector. – TylerH Aug 12 '20 at 21:26
  • I asked this same question on the Vue forums: https://forum.vuejs.org/t/element-selectors-with-scoped-are-slow-citation-needed/130568 Hopefully there will be someone knowledgeable there that can provide citations/supporting evidence for this claim. It's not even clear if they're referring to slow-down from the browser (performance of CSS selectors in general) or from Vue (adding the `data-` attributes for scoping). Also note that the [current latest version of the style guide](https://vuejs.org/style-guide/) itself says that it is outdated. – V. Rubinetti Jun 20 '22 at 17:51

0 Answers0