JavaScript Tip: Minifying Code

Posted in JavaScript Tips
Tags: , ,

Once you’ve written, tested, debugged, optimized, and finalized all of your code, it’s time to release it into the wild. This is to say: distribute the code on live sites. There’s one more step you could take before doing so: minify the code.

To minify code is to remove all of its comments and extraneous white space in order to condense the code as much as possible. Minifying a script will significantly reduce its file size, perhaps by as much as 50 percent. This in turn makes the site load faster in the browser, as there will be less data for the user to download.

There are a couple of tools you can use to minify code. A simple solution is Minify JavaScript (www.minifyjavascript.com), a Web-based solution. Just paste your code into the top textarea, click the Compress JavaScript button, and the minified version will appear in the second textarea.

Then, take the minified code and paste it into a new script, named filename. min.js (e.g., tasks.min.js). Conventionally, the .min is added to indicate minified code. Be certain not to replace the original code or file, as you will lose all of your comments and original formatting during the minification process.

Another Web-based option is Packer (http://dean.edwards.name/packer/), by Dean Edwards. Packer takes minification a step further, also shortening variable names, which condenses the code even more.

More thorough minification can be accomplished using a command-line tool such as:

Leave a Reply

Your email address will not be published. Required fields are marked *

*