Saturday, February 19, 2011

CSS & Javascript Compression

Hi,

Sometimes it is necessary to load js and css which are huge in size, which at the end of the day effects the websites performance. This post will help you in compressing your css and js files on the go. The methods of coversion is basically the same for both, but i will still give the required code indivisually.

CSS Compression:


first create a .htacess file and place it in the css directory where all your css files are placed. The content of this file is:

AddHandler application/x-httpd-php .css
php_value auto_prepend_file gzip-css.php
php_flag zlib.output_compression On

create another file, "gzip-css.php" in the same directory and place the following code in it:

<?php
@ob_start ("ob_gzhandler");
header("Content-type: text/css; 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);
?>

JS Compression

Like css create another .htaccess file in the directory where all you .js files are kept and put the following in the file:

ForceType application/x-httpd-php
 php_value auto_prepend_file gzip-js.php

Create another file, gzip-js.php in the same directory and place the following code in it:

<?php
   @ob_start ("ob_gzhandler");
   header ("content-type: text/javascript; charset: UTF-8");
   header ("cache-control: must-revalidate");
   $offset = 60 * 60;
   $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT";
   header ($expire);
?>
That's it. All the css and js calls you make in any part of your website will get downloaded in compressed format. It also helps improve your YSlow rating for your web pages.

This solution is completely independent of the framework or open source that you are using.

Best of Luck!!

1 comment: