0

According to Vue docs here:

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

So if you put the following in the Vue's style section:

<style scoped>
  .parent .child { 
    background-color: red;
  }

  .parent p {
    background-color: red;
  }

</style>

The VueJs will transform it into this:

<style>
  .parent[data-v-12345] .child {
    background-color: red;
  }

  .parent[data-v-12345] p { 
    background-color: red;
  }
</style>

The document says, the second selector is many times slower than the first one.

Can someone explain why the second selector is slower?

evolon
  • 1,276
  • 1
  • 10
  • 18
  • well ( and this is just a guess ) . If you are more specific ( using a class ) the element can be found faster. I presume in your example the number of `.class` and `p` elements are equal. – Mihai T Feb 21 '20 at 12:23
  • Well this might be correct in general but Vue document clearly says you get a performance penalty when `p` is following `[some-attribute]`. That's what I'm curious about. – evolon Feb 21 '20 at 12:25
  • The reason is because browsers match CSS from right to left https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left. It's nothing specific to the `p` tag. It's that the specificity gains of using an ID/class are reduced/lost when a generic tag selector follows it. – Dan Feb 21 '20 at 12:46
  • So @Dan based on what you're saying, there's also nothing specific about the attribute selectors as well. Any selector followed by an element tag, `.parent p` should behave equally bad regardless of the parent selector. – evolon Feb 21 '20 at 12:53
  • Yeah, I think the idea is that the renderer has to traverse up the DOM to check each parent, grandparent, etc. So it should actually be even slower than a single element selector under certain (all?) circumstances. For example, multiple deeply nested matches. – Dan Feb 21 '20 at 13:03

0 Answers0