cssgulp

Is it worth removing unused CSS?


I am working on a simple web app with 2 other developers at college. We're using a couple of libraries, and packages. I am now trying to get our app ready for deployment, but have notices that it is quite slow. There are a lot of un-used CSS rules.

I tried manually going through compiled styles, searching for references and removing. But this is really tedious.

My question is:


Solution

  • Is it worth removing unused CSS rules?

    I would say yes. To have any unused code in your production build is not cool .

    However, unless something has gone very wrong, it is highly unlikley that your CSS is the reason for slow page loads, in fact the impact of loading a couple pages of unused css rules will be almost neglible. It's more likley to be images/ media, or maybe scripts.

    You should probably investigate whats slowing down your page. Have a look in the network tab of your dev tools to start debugging why page load is slow, Google Page Load Insights may also help. Have a look at this blog series, about speeding up your web apps too.

    If you've not done so already you should probably minify and bundle your CSS and JS for production also.


    How to find and remove unused CSS rules

    Removing unused CSS is a common task, and there are a lot of packages and tools out there which make it strait-forward. There are several options, going forwards:

    1. Manually remove unused CSS.

    If your app is still quite small, this will probably be the easiest approach.

    1. Open Chrome DevTools
    2. Open the command menu with: cmd + shift + p
    3. Type in “Coverage” and click on the “Show Coverage” option
    4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab

    Source: Google Developer, Chrome 59

    2. Use an online tool

    There are tools out there, where you can just feed it a link to your site, and it will search and find unused CSS. The drawback here, is that this won't work locally.

    3. Automate CSS removal

    uncss allows you to automate unused CSS removal, either at built-time, or complile-time. It also works with Grunt and Babel.


    A word of warning, some of your CSS might be detected as unused, when actually you are using it later on, such as when a request has finished loading. Be sure not to delete classes that are indirectly used.

    Edit:

    Be careful when using coverage for CSS usage, it considers media queries, hover effects and others as useless since they're not applied when loading your page

    See also: https://css-tricks.com/unused/