Packing files for faster loading

In my first installement of Fast Web Sites I mentioned the possibility of using a script to serve several Javascript (or CSS) files together to gain speed. Here's a simple and rough PHP script that could do such packaging:

header('Cache-Control: max-age=3600, must-revalidate');
header('Content-type: text/javascript');
ob_start('ob_gzhandler');
if ($_REQUEST['f'])
{ $tab=explode(' ',trim($_REQUEST['f']));
foreach ($tab as $file)
if (preg_match('/^([0-9a-z_\-]+\/)*[0-9a-z_\-]+\.js$/i',$file)) readfile($file);
}

The script is supposed to be installed in the directory where Javascript files are stored. In order to use it you would do something like this to serve up 3 different Javascript files at once:

<script src="/javascripts/script.php?f=file1.js+file2.js+file3.js" type="text/javascript"></script>

A few words on the code :

  1. The output is compressed with ob_gzhandler. This typically shrink the output size by 50 to 75% and gives further speed boost (as well as saving your bandwidth).
  2. For security reasons, the parameter is checked for possible malicious content, using a regular expression that only allows .js files.
  3. HTTP headers are sent to give the proper MIME type as well as make the browser cache the content for 1 hour (3600 seconds), further improving load times

Adapting the script for CSS should be trivial. As it turns out, Rakaz explains and develop the same idea, and goes even further by using mod_rewrite to present a clean URL that hides the packaging script.

0 comment on this post.