Automatically optimize your CSS and JavaScript files with PHP

If, like many people, you like to spread your JavaScript and CSS over a handful of files you may be introducing an unnecessary overhead to your server. If you have a simple page, but 6 CSS files and 6 JavaScript files, users will have to make 13 separate requests to your webserver to load the page. By collating these files you can reduce this to 3 page requests, removing the stress of multiple requests on both the client and server.

Furthermore, assuming you have output compression enabled, the resulting collated file will almost certainly be smaller than the sum of the individual files, due to the way compression algorithms work.

Here's how to achieve this in PHP:

We'll give a description for JavaScript files, as the solution for CSS is identical but for the output tag you need to produce.

First, you'll want to request a collection of JS files to be written:

$script_tag = fetch_script_cache(array('global.js', 'widget.js', 'search.js', 'map.js'));

Now we define our function

function fetch_script_cache($files) {
	// Generate cache index
	$key = md5(join("|", $files));
 
	// Calculate the latest modification to our files
	$max_time = 0;
	foreach($files as $file)
		$max_time = max(filemtime($file), $max_time);
 
	// Prepend the name of the directory where we store the cache files
	$path = "outputcache/$key";
 
 
	// Determine if the cache needs updating, then do it
	if(!file_exists($path ) or filemtime($path ) < $max_time) {
		$cache = "";
		foreach($files as $file)
			$cache .= file_get_contents($file)."\r\n";
		file_put_contents($path , $cache);
	}
 
	return "<script type=\"text/javascript\" src="$path"></script>";
}

The first thing we do is generate an cache index ($key) based on all of the filenames. The we go through all of our files to find out which was the most recently modified, and check if that is more recent than the age of the cache. If it is, the we need to update the cache. The cache file is simply a concatenation of all the files in the list (and we add a line break "\r\n" to avoid any complications).

Our return value is simply a well-formed script tag pointing at the output cache file. The should be outputted in the head of the document, and you're all done!

All scripts are Public Domain.

Comments

nice way to optimize stupid code. Thanks