Compress your CSS
This article has been rendered obsolete by this newer article. Read it for updated and better code.
As all web developers know, CSS files can grow pretty big when building complex websites. Of course we can optimize the size of our CSS by using shorthands and cutting down on comments and whitespace but all of this goes at the cost of readability and maintainability. The best of both worlds would be to be able to work on nicely formatted and well commented CSS files while serving them as optimized as possible to our visitors.
The following handy little PHP script takes care of this! Simply place it in the same directory where your CSS files are and change your <link> tags like this:
<link rel="stylesheet" type="text/css" href="/path/to/cssdir/css.php?file=mycssfile.css" />
You'll be served nicely compressed CSS on the fly while you can happily keep working on mycssfile.css without having to worry about a thing. Let's compress our CSS!
You can see it in action by comparing my uncompressed CSS to the compressed version.
Here's the PHP snippet:
ok, ok this code doesn't render right. I'll fix it tomorrow! For now, get the proper code here
<?php
header('Content-type: text/css');
if (!preg_match("/^([a-zA-Z0-9_-]+.css$)/", $_GET['file'])) {
die('not a css file.');
}
if(file_exists($_GET['file'])) {
$sText = file_get_contents($_GET['file']) or die('Could not open file.');
$sText = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $sText);
$sHash = md5($sText);
header("Last-Modified: ".date("D, d M Y H:i:s T", filemtime($_GET['file'])));
header("ETag: "{$sHash}"");
echo str_replace(array("rn", "r", "n", "t", ' ', ' ', ' ', ' '), '', $sText);
}
else {
echo 'The file named "'.$_GET['file'].'" was not found on the server!';
}
?>
In case you're afraid of this affecting your server performance adversely there's always the possibility of adding a cache mechanism to it. I'll leave that up to you!
Filed under: programming
Number of comments:
Number of trackbacks:
Tagged with: 







At 24 March '07 - 17:34 Oliver Rowlands wrote:
It might be worth outputting the ‘Last-Modified’ and ‘ETag’ headers as part of your response. You can easily obtain the CSS file’s last modification time by using PHP’s filemtime() function.
If you do not include these headers most browsers will re-download the CSS on every page load which would in a way defeat the whole point of this script ;)
Oliver
At 24 March '07 - 18:16 Marco wrote:
At 24 March '07 - 18:26 Pam wrote:
At 27 March '07 - 05:15 Ian wrote:
http://www.roscripts.com/Web_page_optimi..
At 29 March '07 - 04:48 Marco wrote:
I’d personally probably do it differently than he did and rewrite all requests to /some/path/myfile.css to somthing like /csscompressor.php?file=myfile.css and add (like I suggested) some caching to the csscompressor. Same could be done to the JS files.
Leaves us only with the ‘what if there’s multiple CSS files?’ thing. His solution works but it’s not dynamic. When adding a new CSS file the compressor PHP file needs to be added as well. It could probably be done more elegantly by always using one CSS file per page but utilize @import statements in it pointing to additional files. These could be parsed by the php compressor engine and merged into one file.
Maybe I should work all this into an actual example. Who knows, sometime
At 29 March '07 - 10:57 Mike Papageorge wrote:
Here’s another method that I threw together a few years ago for compressing CSS with gzip.
At 29 March '07 - 10:58 Mike Papageorge wrote:
The Definitive CSS gzip Method
At 29 March '07 - 17:31 Marco wrote:
I edited your comment to make it look a bit nicer.
Interesting approach as well I must say!
At 29 March '07 - 17:38 Pam wrote:
I as the average don’t know anything Internet user that I am sure you geeky little boys love..compressing in any style is awesome…if you are stuck on dialup
At 02 April '07 - 13:56 Ozh wrote:
At 06 April '07 - 02:34 Navdeep wrote:
At 28 October '09 - 13:39 Mike wrote: