Wednesday, August 5, 2009

Small bandwidth optimization trick

I've been helping my brother out with his project ( and learning some new tricks in the meantime. One thing that bugged me is that we have a lot of JavaScript files, because we like to keep things separated (one file for the tooltip, one for the autocomplete feature etc.). While this makes developing easier, it's pretty bad for production because it drastically increases the number of requests made by a client. The solution I came up with is a small PHP script that concatenates all the scripts in to one and minimizes everything using JSMin (ported to PHP). This reduces the number of requests to one and lowers bandwidth usage. The code is pretty straight forward: <?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.

No comments:

Post a Comment