Thursday, November 18, 2010

Obfuscating JavaScript with Closure Compiler Advanced Optimizations

While working on our upcoming game, Onslaught! Arena, we wanted to obfuscate the JavaScript code as much as possible. Using tools like YUICompressor and Google Closure Compiler (with Standard Optimizations) just weren’t enough. Luckily, Closure Complier has an “Advanced Optimizations” mode. This mode will really make your JavaScript gross and unreadable!
Here are some cases to watch out for along with some tips for those trying to make their JavaScript as unreadable as possible:
Don’t access object properties as string literals
Using Advanced Optimizations has its pitfalls. Because of it’s super aggressive renaming, Closure Compiler will break your code if you access object properties using string literals. For example:
var thing.stuff = {
   foo: 10,
   bar: 20
};
// This will break after Advanced Optimization :(
var foo = thing["stuff"].foo;
Closure will rewrite thing.stuff as something like a.b and accessing a["stuff"] isn’t going to work.
Don’t use string literals
Closure Compiler won’t obfuscate string literals for obvious reasons so just stay away from them as much as you can!

Read more: Lost Decade Games Blog