Friday, April 20, 2012

Optimizing the JavaScript minification and obfuscation results of YUI Compressor

I have been using YUI Compressor for some time now. According to its documentation it is "a JavaScript minifier designed to be 100% safe and yield a higher compression ratio than most other tools". It is free and compresses both JavaScript and CSS files (including CSS files containing the relatively new CSS3 media queries). You will need a Java Runtime Environment (JRE) to run it. I have integrated YUI Compressor as a tool in Visual Studio 2010, which allows me to minimize JavaScript files that are open in the IDE. You can use the 'External Tools' option in the 'Tools' menu for that.

I am quite satisfied with the results that YUI Compressor offers. However, recently I noticed that it did not change (shorten) JavaScript function names but only (local) variable names. In fact it does change function names, under the right condition. Normally, attempting to replace global function names can result in broken code because YUI Compressor has no way of knowing where else these functions might be used. The solution: Wrap your global variables and functions in a self-executing function and pass in document as an argument:
(function(doc) {
    var helloMsg = "Hello there!";

    function createDiv(message) {
        var div = doc.createElement("div");
        div.innerHTML = message;

In this code, the variable 'doc' is also local to the self-executing function, and so can be replaced by YUI Compressor. The result is:
(function(c){var a="Hello there!";function b(d){var e=c.createElement("div");e.innerHTML=d;c.body.appendChild(e)}b(a)})(document);
This minimized code is 124 bytes (51%) smaller than the original example. Note that YUI Compressor is able to assign shorter names to the helloMsg global variable and the createDiv global function. Because of the wrapper function they are not really global anymore, and the compressor knows that it is safe to rename them.

No comments:

Post a Comment