Your Ad Here

11 February 2011

Best tools that can minify your JavaScript

Why do I need to minify JavaScripts?

Millions of websites have implemented a lot of JavaScript functionality nowadays. It's used almost everywhere: switching tabs, adding cool effects, drag-drop functionality and etc. JQuery JavaScript library is very popular and it's popularity growth every day because it's small, fast and has all basic methods, but still it's not enough to completely cover all required functionality for your custom website (blog, portal, etc.). That forces you to create something new. You will see how the size of your jQuery plugin or simple JavaScript increases as long as you implement new functions, that will increase this script download time (as JavaScript is Client-side, but everyone already know about this ;)). Let's minify your plugin or script to avoid this!

What tool can be used to minify my JavaScript or jQuery plugin?

There are a lot of tools that can be used to minify javascript, but I can recommend you  to see following items:
  1. Dean Edward's Packer
    Why?
    Because it allows you to minify online and also available as .NET, PHP and perl applications and it's easy to use.

  2. Closure Compiler
    Why?
    Because it provides warnings for illegal JavaScript and warnings for potentially dangerous operations, has good documentation, Java application that you can run from the command line.

  3. Microsoft Ajax Minifier
    Why?
    Because it has good documentation, can minify Cascading Style Sheet files (CSS), people who created this tool have huge experience of working with javascript in their library, so they must know what to do to make it smaller and faster.

What result will I get after minifying?

Good question! Let's see what will happen to following code after minifying with Dean Edward's packer:
Original:
function MyMethod(parameter1, parameter2, parameter3)
{
   var myInternalVariable = 'test';
   var myInternalVariable2 = 'code';
   var result = "";
   if (parameter1)
   {
      result = parameter2 + " " + myInternalVariable;
   }
   else if (parameter3)
   {
      result = parameter2 + " " + myInternalVariable2;
   }
   return result;
}
Packed (minified):
function MyMethod(a,b,c){var d='test';var e='code';var f="";if(a){f=b+" "+d}else if(c){f=b+" "+e}return f}

Like this article?