Home » Guides Beginner Article

JavaScript Compression

Not rated
Rate:

Burke Libbey
August 31, 2006


Burke Libbey

Burke Libbey about himself: "I'm a Canadian university student / web developer. I've been developing websites since early 2004, and was the webmaster for a local web design and hosting business for most of the time since then. I was also the PHP programmer for another local business. Now I'm just freelancing it."

http://burke.libbey.name/ 

Burke Libbey has written 1 articles for JavaScriptSearch.
View all articles by Burke Libbey...

Right now, my home page has 42KiB of Javascript. Just a short while ago, that figure was over 100KiB for the same amount of Script. How can this be, you ask? I used JavaScript compression.

As it turns out, there are a multitude of completely free JavaScript compressors online, employing three different basic methods.

Type 1 is the whitespace optimizer. This compressor simply discards all unnecessary whitespace and all comments, without actually intelligently handling any code. This is good because it’s a very low-risk compression. There’s slim to no chance that your script isn’t going to work after, as all the original code is intact. That said, this one offers the least compression. I recommend this to anyone and everyone who uses JavaScript for websites in any significant capacity. Typically, compression is around 80% (20% reduced). See: http://www.creativyst.com/Prod/3/

Type 2 is the smart optimizer. The only example of this one I’ve found was Dojo ShrinkSafe, based on the Rhino engine used in Mozilla Firefox. It parses the JavaScript and rewrites it in the same way as the Rhino engine does. This one can break scripts, so give it a shot, but don’t just expect it to work. My results have varied a little. 50% compression was about average. See: http://alex.dojotoolkit.org/shrinksafe/

Type 3 is the only compressor that uses actual compression, as opposed to rewriting the code. The JavaScript Compressor converts your code into a self-decoding function. I won’t pretend to understand how it all works, but it definitely does. Again, this one can break code too. Sometimes you’ll have to play around with it a little. Make sure you’re not skipping any semicolons. Results for Type 3 compression are typically the best, at anywhere between 50% and 60% reductions in total file size. Check out the JavaScript compressor at http://javascriptcompressor.com/

Before I finish up, just a couple of notes: Remember, any of these compressors can make your code useless (especially the third one), so keep a copy of the original version around. Also, these compressors can be run sequentially. Running code through the Type 2 before the Type 3 typically generated results 5-10% better than using the Type 3 alone.

Good Luck and Enjoy!


Add commentAdd comment (Comments: 0)  

Advertisement

Partners

Related Resources

Other Resources

arrow