Fix "Remove unused CSS" In Lighthouse.

Arjen Karel
linkedin

Remove unused CSS - in short

The warning 'remove unused CS'S in Lighthouse appears when Lighthouse has found too many CSS rules on a page that are not being used at the moment. Because of these 'Unused CSS rules'  the page loads slower than necessary. 

Why? First, there is unnecessary network traffic because the CSS files are larger than necessary. Second, it takes longer to build and apply the CSS objects because more calculations are required.

Fix the warning by removing unused CSS, splitting CSS files per device or using a different CSS strategy. In this article I will explain in greater detail how to fix the lighthouse warning 'Remove Unused CSS'  on your website.

Website Speed Audit

What is Unused CSS?

Unused CSS consists of CSS declarations that are not used anywhere on a web page.
It is quite normal for some of the CSS to not be used. For example, because some CSS declarations are written for another device such as a desktop or mobile. Sometimes  because an element that is described in the style sheet (such as a button) is not used on this specific page.
Unused CSS often occurs when you use a framework such as bootstrap where there are many more elements described by default in the CSS you will ever use. Or when you have redesigned your page but forgot to remove the old CSS elements.

Why is unused CSS bad for page speed?

CSS Slows down the page loading. When a page is loaded, the browser first fetches the HTML from this page. This HTML is converted into DOM Nodes. After that the browser fetches all Stylesheets. The styles found in these CSS files are also converted to another format, namely the CSSOM. The DOM and the CSSOM are combined into a render tree. Only when this render three has been built, a browser starts painting the first content.
Because of this mechanism CSS files will always blocked the rendering of the your webpage. When a CSS file is larger than it should be, it takes longer to download this file and that causes the first delay.  When a CSS file contains unused CSS, it takes longer to build under render tree. 

How to find unused CSS manually?

In Google chrome you can view unused CSS in the Code Coverage overview. Code Coverage is part of the Chrome DevTools. DevTool is a series of built-in tools that are available on every Chrome browser. 

First open the DevTools with Ctrl-Shift-J shortcut. The type Ctrl-Shift-P  to open the command Palette. Now type 'coverage'. Select coverage and reload the page. You will now see an overview of the CSS and JavaScript files that are loaded and used by the page. In addition, you can see how large the files are and how much of the code code is being actually used.
Show CSS coverage DevtoolsClick on a CSS file to see which CSS rules are (green) and which CSS rules are not (red) used on the current page. 

How resolve the 'remove unused CSS' warning

There are several ways to resolve the 'remove unused CSS' message in lighthouse. If, for some reason, fixing the warning is not possible, you could optimize CSS delivery to ensure that unused CSS has less impact on the loading time of your page. I will briefly discuss the options you have for fixing unused CSS below.

1. Delete the unused CSS by hand

The most logical and best way, but also the most laborious way, is of course manually removing the unused CSS. The steps are straightforward:

  1. Backup your CSS original files. You might remove too much CSS.
  2. Open the Code Coverage Tab in Google Chrome and view per CSS file which declarations you do not need.
  3. Open the CSS file on the server (or locally) and check each unused CSS declaration . Determine whether it can be removed. But de careful: a unused CSS declaration does you will never need this declaration. You have to judge that yourself!
  4. Check per CSS declaration whether it is not duplicated in the CSS. Duplicate CSS will also be flagged as unused. 
  5. Check each CSS rule for shorthand methods.  Is is possible to shorted the CSS? Then shorten it!

2. Split the CSS into several files

There is a simple wat  to quickly reduce the number of CSS rules! Only load the styles you need for your device. Your page is often visited on mobile. You don't actually need to download the styles for desktop and print for this mobile device. Not downloading these styles saves time and thus shortens the critical request chain in the lighthouse.

To accomplish this use the media attribute. The media attribute ensures that a stylesheet is only used if the media attribute matched the media you are currently using.

<link href="all.css" rel="stylesheet" media="all">
<link href="print.css" rel="stylesheet" media="print">
<link href="desktop.css" rel="stylesheet" 
 media="screen and (min-device-width: 1024px)">

3. Use an automatic CSS-clean-up tool

There are a number of smart tools that can automatically clean up your CSS files for you and remove any unused CSS references.
While tools work amazingly well they are not flawless. Sometimes these tools remove too many CSS declarations. So use them carefully and always check your CSS yourself.
The best CSS clena up tools are PurifyCSS and PurgeCSS . These tools run on NodeJS. NodeJS is a JavaScript runtime, on which you can execute JavaScript scripts, based on the V8 JavaScript engine from Google itself.  You can also try purifyCSS online.

4.  Critical CSS

Critical CSS is a collection of CSS rules that are needed in the viewport (the visible part) of your website. In other words:  Critical CSS is the CSS that is required to render the visible part of your page.

There are a number of tools that can filter that can extract CSS for from your page. The Ciritcal CSS is then placed inline, in the head of your page, while the original CSS files is loaded asynchronously (for the browser to use later).

This does not completely solve the problem of unused CSS. Eventually the unused CSS will be loaded and parsed but your browser will not be 'bothered' by it during the first render phase.

The most commonly used tool to find and extract critical CSS is the NodeJS script Critical . There are also online tools such as Critical Path CSS Generator and another Critical Path CSS Generator

5. Minify the CSS files

Unused CSS slows down a page, as you read above, in 2 ways. The first is because the CSS files are larger and therefore take more time to download. 

We can counter that issue by reducing the CSS file size by minifying the CSS files. That is done though a CSS minfier.  A CSS minfier shrinks CSS files by removing spaces, comments and formatting. Also, a CSS minifier can rewrite variables and CSS code so that the takes up less bytes to transfer.

A well-known CSS minify tool is css-minify . Minify all your CSS files via the command line with the command css-minify -f filename. There also are various online CSS minifiers such as cssminifier.com

6. Recompile your CSS framework

Are you using a CSS framework such as bootstrap CSS? That is a CSS framework with which you can style your entire site. This framework is so complete that chances are you will never use large parts of it.

Fortunately, the makers of bootstrap and other CSS frameworks have taken this into account. This framework is written in SASS. That is a language that is very similar to CSS. It consists of several small SASS files that can use simple variables and functions. This makes it easy to adjust and personalize  the framework yourself with a little bit of knowledge. You can just omit parts you don't use and easily compile it into 1 final CSS file.

Also make sure you don't load a CSS framework unmodified from the standard CDN. Download the framework and compile it with SASS exactly as you want it, with only the CSS classes you use.

7. Consider a different CSS strategy

Do you really want to be fast? Then it might be a idea to rethink your CSS strategy. How that is done depends on your site. There are several roads that lead to Rome.

Let's take our site for example. We only load the CSS that we actually  need per page. The CSS classes are automatically imported by our CMS only when they are needed. We place the CSS inline (in the head of the page). That saves us an extra network request. This solution is lightning fast and easy to maintain.

An attentive reader might think: "What about CSS Caching, CSS is faster when the final CSS files are cached. Yes, that's right. That's why we preload all links in the visible viewport so that a page is always retrieved from cache, including CSS.

Fix 'remove unused CSS' in Wordpress

Are you ready to remove unused CSS? This if how to get started in WordPress. In WordPress CSS can be added in 3 ways:

  • Directly into the template . In your template folder there is a file called header.php. In this file there are often template specific CSS files. You could modify these CSS files like I described above. Don't forget to backup your original CSS files and keep in mind that a theme update can overwrite your CSS files.
  • CSS added by a plugin . Plugins in WordPress can add unlimited CSS files into your HTML. These plugin use the functions wp_register_style and wp_enqueue_style. Most plugin do not bother too check if they are active on the current page. They just inject CSS into every page, even though there is no need for that plugin specific CSS on that page. I come across that every day. If that is the case, you can use the functions wp_dequeue_style and wp_deregister_style to remove these styles from the pages. That is a precise job. If you are unsure how to fix this, turn to your developer or ask me for help. You can also use the Asses CleanUp plugin with which you can set per page type which plugin, styles and scripts may be loaded.
  • CSS added by JavaScript . It is also possible to 'inject' Sylesheets into the page using JavaScript. Just like stylesheets, you can disable these Scripts per page with the wp_dequeue_script function . When the JavaScript doesn't load, the stylesheet will not be injected either.
    If you do need the script and the stylesheet but not directly after loading, itś possible to postpone the loading of JavaScript via the script defer attribute. Do that by adding this code in functions.php
function defer_js( $url ) {
    if ( is_user_logged_in() ) return $url; //don't break WP Admin
    if ( strpos( $url, 'somescript.js' ) ) {
        str_replace( ' src', ' defer src', $url );
    }
}
add_filter( 'script_loader_tag', 'defer_js', 10 );
lighthouse 100 score

Let's talk about PageSpeed

Tell me about your pagespeed goals. I am a Core Web Vitals consultant and I help speed up websites.