Compress your CSS

Saturday Mar 24 2007

This article has been rendered obsolete by this newer article. Read it for updated and better code.

As all web developers know, 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 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 on the fly while you can happily keep working on mycssfile.css without having to worry about a thing. Let's our CSS!

You can see it in action by comparing my uncompressed CSS to the compressed version.

Dark Matter Pro: a premium photoblog template.

Affiliate program available

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!

bookmarking

Commentary

Join the discussion! Leave a comment through the comment form below!

Got something to add to this?

Feel free to leave a comment on this site. You can use Textile and Emoticons. Your email address is only used to show a gravatar. Please stay on-topic and use common decency. Spammers will be shot in front of a live studio audience.

If you plan on posting code, use pastebin please and post a URL to the code. The comment processing doesn't deal very well with code. Sorry for the inconvenience.

Human comment spammers: don't bother posting your crap here. Comments are moderated and I won't let any of your shit through.

Remember personal info?
Yes
No

Trackbacks

If you have an interesting related post on your own site you can leave a trackback. As they say: 'a little AJAX a day keeps the spammers away' which is why you'll have to click below to generate a trackback key. The key will be valid for 15 minutes and can be used only once.

 

  • Featured Links
RockySomewhere near the Orion NebulaBookalicio.usGolden Gate BridgeThames River BankJackie and mePimpin' it