Confidently removing CSS selectors with Google Analytics
March 8th, 2015 Leave a reply
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
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.
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.
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.
Result in GA
The following image is from Google Analytics and shows a report of the selector usage.
Pros and Cons
- All browsers that hit your site will be included in the tracking.
- Developer effort level is very low, once the selector to track is chosen.
- 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