Blogs

Web vitals: Improve your website speed by removing unsed CSS

Introduction

One time, I was checking my website's web vitals score, and I noticed that it had a performance of around 80.
I started looking for ways to make my website load faster, and one of the issues I found was that there was a lot of unused CSS code.
That was because I'm using Bootstrap 5, and if you're not careful when importing it, you will probably be importing tons of unused CSS.

If you want to check your website's web vitals score also, you can do it here: PageSpeed Insights

The issue with having lots of unused CSS code is that it increases the size of the files it loads, which increases the loading time.
Luckily, I found an easy way to import just the CSS code my website uses!

Solution

The solution is a library called uncss, check it here.
There are many ways you can do it, but I prefer using it as below

  1. I run/serve my website locally.
  2. I created a NodeJS script to run through the available pages on my website and check which CSS is used.
    var uncss = require("uncss");

    options = {
    htmlroot: "public",
    stylesheets: stylesheetsFilesURLs
    }

    uncss(pagesURLSArray options, function (error, output) {
    fs.writeFileSync(`path-to-output-file/output.css`, output);
    });
  3. Once the script finishes, it creates a new file with only the used CSS.
  4. I replace the Bootstrap imports with the output file.

Summary

Mumen.blog's Web Vitals Score from PageSpeed Insights

Mumen.blog's Web Vitals Score from PageSpeed Insights

After doing this, my website's performance score increased from 80 to 100 on desktop and from 80 to 93 on mobile, which is fantastic!