Uncategorized

Confidently removing CSS selectors with Google Analytics

As time goes by CSS builds up as we add features, but more often than not we don’t remove the CSS that’s no longer needed. The reason we leave things lying around could be:

We’ve got a few techniques up our sleeves to assess what might be a good candidate for removal:

Even with these techniques we can’t get close to 100% confidence that a piece of CSS isn’t in use. Sometimes the use is hidden from us, eg an old browser or a CSS class added by a piece of JavaScript.

So I’m proposing another weapon in our arsenal: Google Analytics.

How can GA track CSS use?

Google Analytics includes a way to record custom events using a call to an image file:

http://www.google-analytics.com/collect?v=1&tid=[GA ID]&cid=[USER ID]&t=event&ec=[EVENT CATEGORY]&ea=[EVENT ACTION]

To track CSS usage with this you can use this URL with ‘background-image’, this will register an event each time the CSS selector is triggered.

Basic example

For example the following CSS would register an event for every page request (as an HTML tag is present on every page).

The user is set to ‘css’, the category is ‘cssaudit’ and the action is the same as the selector you want information about.

html {
background-image: url("http://www.google-analytics.com/collect?v=1&tid=[GA ID]&cid=css&t=event&ec=cssaudit&ea=html");
}

With this technique you can identify CSS selectors that you want to know their usage level, add the tracking image, then wait a few days to receive a number reflecting it’s use.

Real life example

The following CSS was included in david-lewis.com on March 2nd. This CSS selector is only triggered on the homepage.

.home {
background-image: url('http://www.google-analytics.com/collect?v=1&tid=UA-11491148-1&cid=css&t=event&ec=cssaudit&ea=.home');
}

Result in GA

The following image is from Google Analytics and shows a report of the selector usage.

Screen Shot 2015-03-09 at 11.30.37 am

Pros and Cons

Pros

Cons