How to compress JavaScript files
Posted: Tue Feb 23, 2010 1:51 pm
You can save bandwidth by pre-compressing your JavaScript files with gzip without relying on dynamic compression such as mod_deflate. To to this properly and having it working across all browsers you’ll need to modify your webserver to return the correct mime type and encoding for the file.
Most browsers are quite liberal in what they accept, except for Safari/Konqueror. For some reason it doesn’t like it if a JavaScript file ends in .gz, it ignores the content-encoding and attempts to read the compressed data as JavaScript. The key to make it work is to create a new extension, for example .jgz and set the Content-Encoding for this extension to gzip AND to set the mime type of .js to text/javascript, not text/plain or application/x-javascript.
To recap, call the file script.js.jgz and make sure your webserver delivers it with the following options
Just include the file as usual
This has been tested with the following browsers
thttpd
Add jsz gzip to mime_encodings.txt and change the type for js in mime_types.txt to js text/javascript.
Most browsers are quite liberal in what they accept, except for Safari/Konqueror. For some reason it doesn’t like it if a JavaScript file ends in .gz, it ignores the content-encoding and attempts to read the compressed data as JavaScript. The key to make it work is to create a new extension, for example .jgz and set the Content-Encoding for this extension to gzip AND to set the mime type of .js to text/javascript, not text/plain or application/x-javascript.
To recap, call the file script.js.jgz and make sure your webserver delivers it with the following options
Code: Select all
Content-Encoding: gzip
Content-Type: text/javascript
Code: Select all
<script type="text/javascript" src="script.js.jgz"></script>
- Firefox 3.0/3.5
- Opera 10
- Internet Explorer 7
- Konqueror (webkit based, behaves like Safari)
- Google Chrome 3
- Epiphany
- Apache
Code: Select all
AddType text/javascript .js
AddEncoding gzip .jsz
Add jsz gzip to mime_encodings.txt and change the type for js in mime_types.txt to js text/javascript.