Gzip Your CSS and JavaScript

When I finished implementing my site, I decided to check it’s YSlow grade. And lo and behold, it got a “C”. So, as I was knocking each markdown off my report card list, I came across an item “Compress components with gzip”. I’ve read about it and kinda understand it, but i had never actually performed this type of compression.

Since I’m on a Mac, I decided to locally compress my files thru the Terminal app. The process I used can be found here. I went with his Option 1 (Compress locally and upload). ┬áThe command I used in Terminal is the following (where yourcssfile is the name of your css file. Ha!):

gzip -c --best yourcssfile.css > yourcssfile.css.gz

After gzipping the css file, I then did the same thing with my JavaScript files. Then, I uploaded these two new gzipped versions of my files to my webhost and changed my references in my HTML files.

I modified my .htaccess file again based on the link above and used the following:

<files *.js.gz>
AddType "text/javascript" .gz
AddEncoding gzip .gz
</files>
<files *.css.gz>
AddType "text/css" .gz
AddEncoding gzip .gz
</files>
RewriteEngine on
#Check to see if browser can accept gzip files.
ReWriteCond %{HTTP:accept-encoding} gzip
RewriteCond %{HTTP_USER_AGENT} !Safari
#make sure there's no trailing .gz on the url
ReWriteCond %{REQUEST_FILENAME} !^.+\.gz$
#check to see if a .gz version of the file exists.
RewriteCond %{REQUEST_FILENAME}.gz -f
#All conditions met so add .gz to URL filename (invisibly)
RewriteRule ^(.+) $1.gz [QSA,L]

I refreshed and my page came up quicker and my YSlow score improved. Yay! Success!

Update: The above worked in all browsers except IE9 (at least for me). So, I replaced the above code with the following:

<IfModule mod_headers.c>
# Serve gzip compressed CSS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
# Serve gzip compressed JS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
# Serve correct content types, and prevent mod_deflate double gzip.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
<FilesMatch "(\.js\.gz|\.css\.gz)$">
# Serve correct encoding type.
Header set Content-Encoding gzip
# Force proxies to cache gzipped & non-gzipped css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
</IfModule>