Friday, January 23, 2009

On the fly JavaScript Packing - Speed up your site!

Minification of javascript has many benefits. One thing that is a pain for developers is remembering to pack your javascript before deployment. Another big pain is if you need to do an on-server change of some JavaScript code. Using Packer JavaScript en PHP a small PHP file and a tweak to .htaccess you can minify your JavaScript on the fly and never again have to worry about minifying your javascript.

First, download the Packer JavaScript en PHP and extract class.JavaScriptPacker.php to some location on your server.

Now create a .PHP file with the following code.

require 'class.JavaScriptPacker.php';
$script = file_get_contents($_REQUEST['js']);

$packer = new JavaScriptPacker($script, 'Normal', true, false);
$packed = $packer->pack();

echo $packed;


Next, bust open the .htaccess and add the following. Note you should have mod_rewrite enabled and mod_rewrite set to ON. If you dont know how to do this, contact your sysadmin or check it out on apache's website.

RewriteRule ^(.+)\.js$ jsProxy.php?js=/$1.js

Now, the concept here is pretty simple. You take any .js javascript file and route it through the proxy. Once the proxy gets it, the packer compresses it.

Need to exclude a file? Simply make it .jsx or some other extension other than .js, the browser doesn't care but mod_rewrite will ignore it.


MPMG said...

What would be the Mod_rewrite rule to reverse the js rule that you could apply to a htaccess file in other folder?

Rob said...

Reverse it? You mean not compress it? The easiest way to handle this is to change .htaccess to look for .jsx instead of .js and then you can selectively compress instead of selectively exclude.

Yellow Blade said...
This comment has been removed by a blog administrator.