Optimizing your JS and CSS

Standard

My coworker Ryan Doherty loves front-end optimization. A lot.

So much, in fact, that he’s working on bringing it to the masses.

I just wanted to blog quickly to show the difference CSS and JS compression can make on perceived load time. I encountered this when working on a new mozilla.com page for download stats.

First, let’s look at how we were at the beginning:

Document Complete Fully Loaded
Load Time First Byte Start Render Time Requests Bytes In Time Requests Bytes In
First View 16.795s 0.992s 13.086s 16.795s 51 309 KB 16.795s 51 309 KB
Repeat View 2.533s 0.883s 1.622s 2.533s 5 19 KB 2.533s 5 19 KB

Next, let’s look at how we were after we concatenated and minified all our JS using YUI compressor:

Document Complete Fully Loaded
Load Time First Byte Start Render Time Requests Bytes In Time Requests Bytes In
First View 11.546s 0.933s 6.455s 11.546s 38 242 KB 11.546s 38 242 KB
Repeat View 2.679s 0.919s 1.671s 2.679s 5 19 KB 2.679s 5 19 KB

Finally, after some prodding from Ryan, I concatenated and minified all CSS:

Document Complete Fully Loaded
Load Time First Byte Start Render Time Requests Bytes In Time Requests Bytes In
First View 10.892s 0.826s 5.732s 10.892s 35 238 KB 10.892s 35 238 KB
Repeat View 2.285s 0.881s 1.435s 2.285s 5 20 KB 2.285s 5 20 KB

In summary, concatenating JS and CSS can make a huge difference, and I saw it today. Here was the progression:

  • 13.086s – nothing
  • 6.455s – JS minified
  • 5.732s – CSS minified

We saved about 56% of our load times and reduced the overall number of HTTP requests by 31% (38 down from 51).

Took me about 30 minutes to figure it all out and fix some 404s and path issues caused by moving CSS around. 30 minutes for that kind of improvement is worth the investment.

Note, you’re going to want to automate using the compressor. It becomes a pain in the ass to manage over time unless you do. But it’s not hard to write a build script to run every time you make an update. It’s also not difficult to have production vs. development flags in your site config to flip which css and js files it uses so you don’t spend time trying to debug a minified bumble of JS or CSS. Even with minor maintenance and deployment hurdles, it’s still very worth the trouble.

And don’t forget, less HTTP requests and bytes transferred means a happier planet.

Update: after pushing to production, performance was even better:

Document Complete Fully Loaded
Load Time First Byte Start Render Time Requests Bytes In Time Requests Bytes In
First View 3.707s 0.906s 3.365s 3.707s 40 301 KB 4.933s 48 313 KB
Repeat View 0.129s 0.601s 0.496s 0.129s 2 1 KB 0.781s 4 2 KB

So yes, it does help to have fast servers, good hardware load balancing, and a quick proxy cache too. :)