Easy javascript packing with PHP

Posted February 5th, 2009 by Juozas

“JavaScript packing” is method for reducing JavaScript files size by removing all unnecessary data (obfuscating) and compressing it’s contents. Most popular is Dean Edward’s packer, which transforms JavaScripts into something like this:

eval(function(p,a,c,k,e,r){...

To start with, it’s very easy to have dynamically packed files (no one wants to pack them by hand, packed versions are only useful for production, debugging them is harder) with PHP. One of many PHP packers is available on-line at http://joliclic.free.fr/php/javascript-packer/en/. It’s simple one-file script which works really well.

JavaScript packing is as simple as:

require 'class.JavaScriptPacker.php';
 
$src = 'my_script.js'; // Script file
$script = file_get_contents($src);
 
$packer = new JavaScriptPacker($script, 'Normal', true, false);
$packed = $packer->pack();
 
header ("Content-type: text/javascript; charset=utf-8");
header ("Content-Length: " . strlen($packed));
echo $packed;

* Parameters for JavaScriptPacker object can be easily tested in project website. Sometimes packed javascripts don’t work because of missing “;” symbols. I used FireBug extension for Firefox to find actual problematic lines in unpacked version and correct them.

Using this class I created controller for all my JavaScripts, which gets JavaScript name from GET call, checks for cached version and if packed version is not cached – creates 1 day cache and outputs it. Also, I pass JavaScript name in special form: “filename1-filename2-… .js” what let’s me merge multiple files into one packed version. (it can be optimized even more by storing cached versions as static files and accessing them directly)

Packer alone cannot make a big difference, but by combining it with:

  • multiple files merging
  • caching (correct headers)
  • then packing
  • putting JavaScripts at the bottom of document

gives very good results, not only decreasing HTTP calls count, but also time required to render whole website. Still, it’s very easy to implement whole system since all required libraries (packer, caching, etc.) are available on-line for free.

Comments (1)

  1. Rheba Zanardi

    Hey, I came across this article while searching for help with JavaScript. I have recently switched browsers from Opera to Microsoft IE 6. Just recently I seem to have a problem with loading JavaScript. Every time I browse site that needs Javascript, the site freezes and I get a “runtime error javascript.JSException: Unknown name”. I can’t seem to find out how to fix it. Any aid is greatly appreciated! Thanks

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">