Techno WeBlog

blogging about tech, the tech, and everything tech, for techno addicts!

Join Techno Google group

Need for speed : CSS Compression

A powerful advantage of using PHP is that you can compress your files so that they take up less room on your server. There are multiple ways of achieving this, one method is as follows:

ob_start(”ob_gzhandler”);
?>

Just add that to the very beginning of main.php or global.php or whatever. Right now the file may be very small anyway, but in a real-world situation it would contain much more code. You’ll soon see the speed benefits of this simple file compression method.

You can import your CSS as a PHP file. This offers you a range of options for creating CSS on the fly using arrays and variables and means you can compress your style rules too. Just add this PHP header to the beginning of your CSS:

ob_start (”ob_gzhandler”);
header(”Content-type: text/css”);
header(”Cache-Control: must-revalidate”);
$offset = 60 * 60 ;
$ExpStr = “Expires: ” .
gmdate(”D, d M Y H:i:s”,
time() + $offset) . ” GMT”;
header($ExpStr);
?>

Remember to save your CSS file with the PHP extension and import it properly.You can do this as follows……..

@import url(mycss.php);

The above method, though not as clean, it is just as effective. All you need to do is place the PHP snippet from above into the top of your CSS document. Then, rename your CSS file with a ‘php’ extension, and then refer to that file when linking your css file. Thats all….

Alternative Method
=================
The following method is cleaner and more elegant, as it does not require the addition of any extra code to your CSS file, nor do you have to change the extension of the file. Clean and simple.

Two steps are necessary to implement this method.

Step one:
First, you want to save the snippet provided above in a file called ‘gzip-css.php’ to the directory that contains your CSS files.

Step two:
Here, simply add the following to an .htaccess file and save the file to the same directory as your CSS files:

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

This code does 3 things:

1. The first line tells Apache to send all .css files to the PHP script handler.
2. The second line prepends the code snippet to your CSS file.
3. The third line tells PHP to use its built-in negotiated output compression automatically for every page it parses. This is optional. If you use this method for compression, there is no need for having ob_start (”ob_gzhandler”); in the code snippet.

So in this way you can keep your CSS file as it is without any name change.

posted by Jansan John @ 8:40 PM,
Labels : DiggIt!  |   Del.icio.us


0 Comments:

Post a Comment

<< Home

Google

Archives

Previous Posts

Links