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:
- Cleaning up old CSS is not seen as important as adding new features.
- We are never 100% confident that the CSS left behind is not in use.
- We add extra CSS to allow for more design options, but those options are never used.
We’ve got a few techniques up our sleeves to assess what might be a good candidate for removal:
- When we’re introducing a new feature that replaces an old one, we know that the old CSS isn’t needed
- Auditing the CSS using tools like DustMe, Chrome’s CSS audit etc
- Searching through the data base and template files looking for occurrences of certain class names
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.
Pros and Cons
Pros
- All browsers that hit your site will be included in the tracking.
- Any CSS selector that’s triggered by a user interaction (ie JavaScript) will be tracked.
- Developer effort level is very low, once the selector to track is chosen.
Cons
- Slow to get results, to get decent results may take a few days
- Doesn’t record data on unused parts of your site during the time you have the event tracking in your CSS
- Doesn’t tell you where on the site the CSS was used