Saturday, June 03, 2006

Compressing HTML, CSS, and JavaScript files

Adding gzip compression to files received from your web server can enhance the network latency of your web application. As simple way to do this is to define a handler in your .htaccess file to compress your HTML, CSS, and JavaScript files. To do this, add these lines to your .htaccess file:


AddHandler application/x-httpd-php .css .html .js
php_value auto_prepend_file /path/to/gzip-page.php
php_flag zlib.output_compression On

where the path is specific to your installation.

The gzip-page.php is needed to define the content-type for the compressed data so that they are not assumed to be PHP files. The code should look something like:


<?php
$pathinfo = pathinfo($PHP_SELF);
$extension = $pathinfo['extension'];
switch ($extension) {
case "css" :
header("Content-type: text/css");
break;
case "html" :
header("Content-type: text/html");
break;
case "js" :
header("Content-type: text/javascript");
break;

default :
break;
}
?>


Now all your HTML, CSS, and JavaScript content will be compressed if the browser supports compressed data (which most do). For Ajax applications this is most useful since you'll probably have a decent amount of JavaScript code to transmit and potentially a fair amount of CSS as well.

No comments: