CSS Minification for Server-Side Rendered Apps

With styles moving into components and critical styles being unique for each layout we no longer get the luxury of preparing and optimizing CSS during the build process (especially for server-side rendered applications). Optimizations needs to happen dynamically and have to be as fast even with a caching layer on top of it.

Most of the HTTP responses these days are compressed using GZIP which takes care of reducing the response body size during the transfer so I’m not completely sure why CSS and JS minification is considered that important in Google PageSpeed, for example. AMP also limits the uncompressed CSS per page to a maximum of 75KB.

Minification vs. Compression

I created this experiment to evaluate the impact of CSS minification over the resulting compressed version and the time it takes to do the minification.

For minfication I used the csso library and this “dummify” three rule regular expression string-replace as the fastest way to do some minification:

const dummyMinifyCss = (css) => {
  return css
    .replace(/[\n\r\t]/gi, ' ') // Line breaks to spaces.
    .replace(/\s+/gi, ' ') // Multiple spaces to single spaces.
    .replace(/(\s+?)?([\(\):;}{>])(\s+?)?/ig, '$2') // Remove spaces before and after :;{}()>
}

Note that I haven’t really tested this tiny minifier apart from this site and a few other sites using the Bootstrap CSS library. I’m using a PHP version of the same snippet with the Minit plugin on this blog.

Results

Here are the results for the Bootstrap CSS library:

SizeCompressedMinify Time
Original198KB26KB
Minified158KB (-20%)24KB109ms
Dummified166KB (-16%)24KB6ms (-94%)

The dummy minifier produced only a 4% larger CSS but 18 times faster than csso with the compressed CSS being the same! Note that different CSS files have different minification potential usually in the range of 5-35%.

Minifying CSS has very little impact over its compressed size so using a fast minifier that removes only the unnecessary whitespace is the quickest solution for server side rendered apps with dynamically generated CSS.

2 Comments

  1. Renato Alves says:

    Since Google Pagespeed is not geared towards SSR only apps, it makes sense to have that as an important metric there.

    Since I’d guess SSR apps are a minority on the web.

    • Kaspars says:

      Looks like I didn’t explain myself well in the post… sorry! The client-side rendered apps are still a minority which is why in this post I was specifically referring to the server-side rendered apps like WordPress, Drupal, Django, Rails and pure HTML websites, and how they use CSS.

Leave a Reply to Kaspars Cancel reply