Compressing Javascript with PHP
I have been learning the Rico Javascript Library this weekend. My only complaint about using any Javascript library is the weight that it adds to my output. By using Rico, I am adding nearly 80k of size per page of delivery of the script. I am not concerned about the load time nearly as much as I am about excess bandwidth.
With that in mind have made a very quick test for compressing Javascript with GZIP via PHP. This method is inspired by Fifty Four Eleven's post on compressing CSS with GZIP. In fact, I am using the same script, but changing the header type to text/javascript vice text/css.
For the code I followed the first method and inserted this into the Rico Javascript files:
I am simply using the same expiration as the original CSS tutorial provided. If you like, change the $offset to something higher and thus the cache will be held that much longer.
In your HTML you just need to call your Javascript in a different manner:
vice the normal:
The second method listed on the original CSS compression tutorial will work as well. In your .htaccess though you will want to change the extension name:
Code:
AddHandler application/x-httpd-php .js
php_value auto_prepend_file gzip-js.php
php_flag zlib.output_compression On
Thus you will also want to create gzip-js.php with the changes mentioned above.
With my test I used Firefox 1.0.4 and IE 6.0 with no ill effects. My guess is IE 4 and NN 4 will not like this method any more than they like the CSS compression method, so buyer beware. Using the compressed method caused the javascript size to decrease to little over 16k vice the original 80k with the non-compressed method. This is a dramatic change with this example.