From Johnny's dev blog:
The challenge: Calculate the real percentage of unused CSS
Our goal is to create a script that will measure the percentage of unused CSS of this page. Notice that the user can interact with the page and navigate using the different tabs.
DevTools can be used to measure the amount of unused CSS in the page using the Coverage tab. Notice that the percentage of unused CSS after the page loads is ~55%, but after clicking on each of the tabs, more CSS rules are applied and the percentage drops down to just ~15%.
That's why I'm so skeptical of anything that attempts to measure "unused CSS." This is an incredibly simple demo (all it does is click some tabs) and the amount of unused CSS changes dramatically.
If you are looking for accurate data on how much unused CSS is in your codebase, in an automated fashion, you'll need to visit every single URL on your site and trigger every possible event on every element and continue doing that until things stop changing. Then do that for every possible state a user could be in—in every possible browser.
Here's another incredibly exotic way I've heard of it being done:
- Wait a random amount of time after the page loads
- Loop through all the selectors in the CSSOM
- Put a
querySelectoron them and see if it finds anything or not
- Report those findings back to a central database
- Run this for enough time on a random set of visitors (or all visitors) that you're certain is a solid amount of data representing everywhere on your site
- Take your set of selectors that never matched anything and add a tiny
1pxtransparent GIF background image to them
- Run that modified CSS for an equal amount of time
- Check your server logs to make sure those images were never requested. If they were, you were wrong about that selector being unused, so remove it from the list
- And the end of all that, you have a set of selectors in your CSS that are very likely to be unused.
Clever, but highly unlikely that anyone is using either of these methods in a consistent and useful way.
I'm a little scared for tools like Lighthouse that claim to audit your unused CSS telling you to "remove unused rules from stylesheets to reduce unnecessary bytes consumed by network activity." The chances seem dangerously high that someone runs this, finds this so-called unused CSS and deletes it only to discover it wasn't really unused.