Skip to content

Stop Concatenating Your CSS/JS

Remember when concatenating all your CSS and Javascript files into one was a best practice? Not anymore.

Published on

Concatenation is dangerous

Merging all your Javascript files into one may save browser requests, but it also means that a single error in one of your scripts will screw up everything.

Even if your Javascript is technically free of errors, old browsers like IE8 lack support for otherwise normal javascript such as function.prototype.bind(), get and set keywords, etc.

TL;DR: Eventually, stuff will fail. Concatenation will just make things fail harder.

Concatenation is bad for caching

You bundle all your Javascript (could also be CSS) and push to production. Your bundle.js file gets cached by both your CDN and your user’s browsers. Nice!

But now you need to fix something. As usual, you work on your code, and re-bundle all your scripts. Then you push.

Since your bundle.js is actually a new file (fingerprinted with a new MD5 hash), the cache is invalidated.

Every time you concatenate your files into a single bundle, you force users to re-download the entire bundle every time you make a change no matter how tiny.

By including smaller files separately, you allow browsers to cache those Javascript and CSS bits that don’t get updated frequently, giving you higher cache hit ratios and improved performance.

Say hello to HTTP/2

Concatenating your files used to serve the purpose of reducing HTTP requests. Under HTTP/1, downloading one big file will (almost always) be faster than performing many requests to download multiple smaller files.

This is not the case with HTTP/2, where requests are very cheap. This is mainly because of the protocol’s ability to re-use connections, compress headers and multiplex.

But… not so fast

While caching improves with multiple files, compression usually gets worse. Because of how compression algorithms work, they usually do much better on large, monolithic files than smaller ones. That means you are now serving bigger files.

This needs to be tested on a case by case basis. If you are serving hundreds of multiple files, you may want to bundle them in smaller chunks. For a couple dozen, it probably won’t be worth the hassle.

Can I Use HTTP/2 today?

At the time of writing this article, HTTP/2 has over 77% global support. It’s also backwards compatible, so the short answer is yes, you can get started with HTTP/2 today.

Amazon Cloudfront supports HTTP/2 since September 8th and there are tutorials for DigitalOcean as well.

So what about those browsers that don’t support HTTP/2?

Slow is always better than broken. And HTTP/2 is not a magic bullet either. You still want to take advantage of other web performance techniques out there. For example: some browsers that don’t support HTTP/2 do have support for other “modern” features like resource hints.

Join my newsletter and get articles like this delivered straight into your inbox.