GZIP Compression and Javascript Minification

Compressing content on server before sending it over HTTP is a good practice since it saves a lot of traffic and makes transfers faster.
For example, Prototype.js is 123KB size and after Gzip compression it becomes only 28KB.
GZIP Compression also affects HTML so even primed cache requests that downloads mostly only HTML will be faster.

So we should enable server-side compression of textual components: Stylesheets, Javascript, HTML, XML (there is no need to compress images as they already compressed).

For Apache2:
compression done by mod_deflate
AddOutputFilterByType DEFLATE text/html text/plain text/css text/javascript application/x-javascript text/xml

For Lighttpd:
enable mod_compress in lighttpd.conf and add configuration directives:
compress.cache-dir = "/tmp/"
compress.filetype = ("text/plain", "text/html", "application/x-javascript", "text/css", "text/javascript", "text/xml")

Nginx configuration directives:
gzip on;
gzip_min_length 1000;
gzip_types text/html text/plain text/css text/javascript application/x-javascript text/xml;

(See ngx_gzip_module documentation for details)

Besides compression there is minification (removing comments and unnecessary whitespaces) that can further reduce size of Javascript.
Minified Prototype.js becomes 92KB size uncompressed and 23KB compressed, this is 20% less than compressed non-minified script.
There are number of tools for minification exists, I’m using JSMin (http://crockford.com/javascript/jsmin).

3 comments ↓

#1 Jason S on 10.20.08 at 8:47 am

I wasn’t able to use the above method on my web host due to their set-up. Alternatively I used php and the zlib extension to compress my files as per the blog below…

http://thewebdevelopmentblog.com/2008/10/tip-speed-up-your-websites-using-gzip-and-merging-files/

The other methods above easier but if you can’t get it to work either look at the link above.

It can also merge your files and cache them to increase loading speed even more.

Cheers!

#2 Nail on 10.30.08 at 7:43 pm

Jason,

Your tool contains a security hole, you should be careful with file_get_contents.
Now it’s possible to send something like gzip.php?f0=/etc/passwd and stole content of files from the server, for example, source code, database password, etc.

But in general, sure it’s a useful tool (if we fix the issue above) and it can be used on hostings where we cannot change server settings.
Also, I would send 1 month expires header (instead of 3 days) and I would send Last-Modified header so browsers will be able to send conditional requests.

#3 Jason S on 11.02.08 at 6:39 am

Thanks for the feedback Rain,

I will update the script to only allow .css and .js extensions to be parsed which would solve this issue.

As for the expiry, 3 days is generally fine for my usage, if people want longer expiries it’s easily changed in the php script.

Thanks again.

Leave a Comment