Laravel optimization : reduce CSS size

Jan 9, 2022 by Thibault Debatty | 7171 views

Laravel

https://cylab.be/blog/193/laravel-optimization-reduce-css-size

CSS files are a render blocking resource: the browser waits for your CSS files to be downloaded before rendering the page. This means that, as long as the browser is downloading CSS, the user is waiting in front of a black page...

Unfortunately, most modern web applications use third party CSS frameworks that usually consist of lots of CSS code. For example, a very simple Laravel application using Bootstrap will generate 202KB of minified CSS code. For a user with a mobile device, this represents roughly 1 second of extra waiting for the page to display...

purgecss-before.png

Luckily, there is a tool called PurgeCSS that automatically removes all unused code from your compiled CSS.

Installation

npm install laravel-mix-purgecss --save-dev

Then modify webpack.mix.js to add 2 lines:

  1. At the beginning of the file, load the module:
const mix = require('laravel-mix');
require('laravel-mix-purgecss');
  1. At the bottom of the file, add purgeCss to the processing chain:
mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .purgeCss();

Now each time you compile your CSS resources with npm run prod, all unused CSS will stripped out, reducing the size of the produced CSS file.

Result

After running npm run prod, the size of the minified CSS is reduced to 26KB, and the blocking time is reduced to 380 ms, one third of the original waiting time...

purgecss-after.png

Caveats

PurgeCSS works by scanning your views to detect the CSS classes that you use. Hence if you are using Javascript code that dynamically writes HTML, these classes will not be detected by PureCSS, and will be removed from final CSS.

As a workaround, you will have to manually whitelist these CSS classes in your webpack.mix.js:

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .purgeCss({
       safelist: ['btn', 'btn-primary', /^nav-/],
   });

The safelist can contain strings and regexes.

You can also find other options on the the site of PurgeCSS.

Going further

Once your CSS is reduced, you can go further optimize your Laravel application with static content caching.

This blog post is licensed under CC BY-SA 4.0