CSS effective selector

CSS optimization

Recently I posted an article about CSS optimization describing five simple steps you can do to speed up the page load time and the bowser execution time. One of the key features is to use effective selectors, but what exactly that means.

Parents and children

In CSS, after the name of cascading, there is a very powerful feature of inheritance and you can simply describe a child style by a selector which can be something like that:

div table tr td a { color: red; }

In reality is very, but very inefficient. Event it is a working example, the browser will find every anchor <a tag within the page than check if it’s child of a td, than tr and so on until the closing outer most div tag.

That’s why the browser is really hard to find every one of these tags just to apply a simple font color. What the big problem is that once you have thousands of tags in that page the browser starts to use CPU and the application starts to be irresponsive.

The solution

Of course there’s a simple solution, which can be described as transformation from inefficient to efficient selectors. Because the browser can find a tag way faster by a given ID or CLASS you can simply convert the code above with something like:

a.my-class { color: red; }

and than change a bit the markup with a tags with that specific class name. Which is a bit tricky, but speedups the performance a lot.

How can I find bad selectors?

Actually that is the big problem. Once you’re into the deep of web development the applications are so big, with so many CSS selectors and so many CSS rules that you simply cannot track that any more.

Hopefully there comes some tools that can describe you everything and point you the inefficient selectors. My personal choice is the Google’s Page Speed plugin, which can be installed to the Firebug on Mozilla Firefox. It can analyze the page and extract a list of inefficient and so called very inefficient selectors that must be fixed!

Leave a Reply

Your email address will not be published. Required fields are marked *