This old site is no longer updated. Visit the new site.

Javascript: Packing, Unpacking, and Beautifying

A lot of the Javascript on the web ships in compressed form. This is particularly irritating if you discover that, say, Drupal 5’s jstools module has bugs that you’d like to fix, but the module ships with nothing but compressed versions of the Javascript code. (What were they thinking?)

A common method of packing Javascript is Dean Edwards’ packer algorithm, which has a convenient online version. You can recognize code that’s been through the packer by looking for the cute function signature at the beginning:

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

It turns out that you can unpack code like this using Dean Edwards’ online tool. This isn’t immediately apparent, because the tool doesn’t enable this feature by default (presumably because it’s trying to pretend that packing is an effective form of code obfuscation). But if you run the handy “reEnable” bookmarklet the packer page becomes an “unpacker” page.

Once your function is unpacked you are only halfway home, because it will look like this example (from the jQuery History/Remote plugin included with Drupal jstools):

(function($){$.ajaxHistory=new function(){var c='historyReset';var k=location.hash;var e=null;var g;this.update=function(){};var h=function(){$('.remote-output').empty()};$(document).bind(c,h);if($.browser.msie){var f,initialized=false;$(function(){f=$('<iframe style="display: none;"></iframe>').appendTo(document.body).get(0);var ...

No line breaks, not so readable. So feed it through the online beautifier for Javascript and you’ll get

(function($) {
$.ajaxHistory = new
function() {
    var c = 'historyReset';
    var k = location.hash;
    var e = null;
    var g;
    this.update = function() {};
    var h = function() {
        $('.remote-output').empty()
    };
    $(document).bind(c, h);
    if ($.browser.msie) {
        var f, initialized = false;
        $(function() {
           ...

Much better.