Making a habit of compressing your Javascript

June 4th, 2009 | Tags: , ,

Ever since I’ve began creating web applications that include more and more Javascript, some of my own, and some such as Javascript libraries and plug-ins, the need for me to optimize the amount of data to transfer to the client becomes more imporatant.  I’ve found that compressing your Javascript is one of the simpliest things you could do and save a few kilobytes on initial page load.

So far, the best compressor I’ve used is the YUI Compressor. YUI Compressor compresses Javascript files by stripping out unnecessary whitespaces, semi-colons, and replace local variable names with shorter names, decreasing the size of the file by about 30% in my experience.

The only few ways to run your code through YUI Compressor is through an online service, or by downloading the YUI Compressor to your computer and running it via command line.  I use the command line, but I’ve made using it a habit and without even having open up command line by just saving the command into my favorite code editors and just assigning a hot key to it. For example, Notepad++ has a ‘Run…’ option that lets you run external executables and saving that command line to some set of hotkeys (e.g. Ctrl+1).  In the command line arguments, you can set editor-specific variables for the filename, etc. such that executing the command can automatically take your script.js that you’re working on, compress it, and output a script.min.js file for you in the same directory.  It’s simple and you don’t even think about it once you have it all set up.  I’ve even made it a habit to compress all 3rd party scripts when possible to squeeze a few more kilobytes out of the overall transfer.

Of course there are other ways to save on transfer such as by making sure your server has GZIP compression turned out, and a few other methods, but making a habit of compressing your Javascript is one of the simplist thing you can do and can go a long way in saving a lot of bandwidth and improve user experience with less loading time.

No comments yet.