<?php
/**
* JS on-the-fly compressor with caching *
* Uses JSMin by Douglas Crockford *
* Author: Felix Oghina *
*/
//-- Configuration --//
$JSMin = 'jsmin-1.1.1.php'; // path to the JSMin class file
$path = '.'; // this can be made dynamic by assigning a value from $_GET, although it may be unsafe
$cache = 'js.cache'; // this file will be used as cache. If it's in the same directory as $path,
// it should not end in .js
//-- End of configuration --//
// include the JSMin script
require_once $JSMin;
// first decide if we use the cache or not
$usecache = true;
$files = glob($path . '/*.js');
$maxtime = filemtime($files[0]);
foreach ($files as $file) {
$curtime = filemtime($file);
if ($maxtime < $curtime) $maxtime = $curtime;
}
if (!file_exists($cache)) {
$usecache = false;
}
elseif (filemtime($cache) < $maxtime) {
$usecache = false;
}
// send appropiate headers
header("Content-Type: text/javascript");
// we use the cache
if ($usecache) {
readfile($cache);
}
// we rebuild the cache
else {
$js = '';
foreach ($files as $file) {
$js .= file_get_contents($file);
}
$js = JSMin::minify($js);
// rewrite the cache
file_put_contents($cache, $js);
// output the js
echo $js;
}
// done
?>
This solution uses caching, so it only minifies after you change something in one of the JavaScript files. In our case, this reduces the number of requests from 5 to 1 and the total size by 6kb (that's six thousand characters). The only flaw (that I see) is that if you delete one of your JavaScript files, it won't update the cache. Although I see the problem, I don't see an immediate solution, so I won't bother with it. It's not like we're going to delete JavaScript files all the time.
Maximum score
2 years ago
No comments:
Post a Comment