DarkCSSCache & DarkJSCache – The best way to compress CSS and JS
November 9th, 2009
1 comment
Download required PHP minify classes
CSS.php:
<?php
require "class.cssmin.php";
$prefix = './';
$files = array("my.css", "another.css");
$contents = '';
$size = 0;
foreach($files as $name){
$contents .= "\n\n" . file_get_contents($prefix.$name);
$size += filesize($prefix.$name);
}
$contents = "/* DarkCSSCache - 100% Pure Win. */\n".cssmin::minify($contents);
file_put_contents("../darkcsscache.css", $contents);
file_put_contents("../darkcsscache.css.gz", gzencode($contents, 9, FORCE_GZIP));
echo number_format($size)." bytes compressed to...<br />".number_format(strlen($contents))." bytes standard<br />".number_format(filesize("../darkcsscache.css.gz"))." bytes gzipped";
?>
JS.php:
<?php
require "../class.jsmin.php";
$prefix = '../';
$files = array("jquery.js", "shit.js");
$contents = '';
$size = 0;
foreach($files as $name){
$contents .= "\n\n" . file_get_contents($prefix.$name);
$size += filesize($prefix.$name);
}
$contents = "/* DarkJSCache - 100% Pure Win. */\n".JSMin::minify($contents);
file_put_contents("../darkjscache.js", $contents);
file_put_contents("../darkjscache.js.gz", gzencode($contents, 9, FORCE_GZIP));
echo number_format($size)." bytes compressed to...<br />".number_format(strlen($contents))." bytes standard<br />".number_format(filesize("../darkjscache.js.gz"))." bytes gzipped";
?>
As you might have guessed, this requires nginx with gzip_static to serve the .gz files. A much older version of DarkJSCache exists for Apache – fire me a message/comment if you are interested.
Anyway, this is by far the most efficient way to serve Javascript and CSS concatenated into a single file, minified and GZipped where the user’s browser allows.
It’s also quite unrealistic for a cron script etc. to check dates and update the files. Much better to do it yourself, so you can see changes almost instantly.
Anyway I use this on Imgkk and it’s certainly very successful there.