Need for speed : JavaScript Compression
This is a continuation to my previous post Need for speed : CSS. I have used PHP to compress my JavaScript files.
Why compression and How?
Javascript files for larger sites can become pretty large themselves. Gzipping or compressing these files has shown to provide a reduction in the neighborhood of 70-80% of the original file size, a fairly significant ‘weight loss’.
With that in mind have made a very quick test for compressing Javascript with GZIP via PHP. I am using the same method mentioned in Need for speed : CSS Post. 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 my Javascript files:
<?php
ob_start (“ob_gzhandler”);
header(“Content-type: text/javascript; charset: UTF-8″);
header(“Cache-Control: must-revalidate”);
$offset = 60 * 60 ;
$ExpStr = “Expires: ” .
gmdate(“D, d M Y H:i:s”,
time() + $offset) . ” GMT”;
header($ExpStr);
?>
heyyy…. dont forgot to rename your javascript file with PHP extension. In your HTML you just need to call your Javascript in a different manner:
<script type=”text/javascript” src=”path/to/javascript.php”></script>
vice the normal:
<script type=”text/javascript” src=”path/to/javascript.js”></script>
The second method will also work as well. In your .htaccess though you will want to change the extension name:
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.
Filed under: JavaScript, PHP, Tips & Tricks
