Great articles, like Dave Hyatt’s “Writing Efficient CSS”, helped developers adapt to a rudimentary selector matching landscape. We learned from Steve Souders (and others) that selectors match from right to left, and that certain selectors were particularly arduous to match and should best be avoided. For example, we were told that descendant selectors were slow, especially when the right-most selector matched many elements on the page. All this was fantastic information when we had none, but as it turns out, times have changed. Thanks to some amazing work by Antti Koivisto there are many selectors we don’t need to worry about anymore.
Antti Koivisto contributes code to WebKit core and recently spent some time optimizing CSS selector matching. In fact, after finishing his work, he said:
My view is that authors should not need to worry about optimizing selectors (and from what I see, they generally don’t), that should be the job of the engine.
Wow! That sounds fantastic to me. I’d love to be able to use selectors in a way that makes sense for my architecture and let the rendering engine handle selector optimization. So, what did he do? Not just one thing, rather he created multiple levels of optimization—we’ll take a look at four optimizations in particular:
Style sharing allows the browser to figure out that one element in the style tree has ...