Introduction
The increased use of JavaScript and libraries based
on JavaScript (such as ASP.NET AJAX and jQuery) results in a considerable amount of
JavaScript being downloaded on the client side. The need for large amounts of
JavaScript to be downloaded may result in your website getting a performance
penalty for obvious reasons. In such cases it is recommended to reduce the size
of JavaScript files by using minification
techniques. To that end Microsoft
Ajax Minifier, a tool to compress JavaScript and CSS files, can greatly
reduce the size of such files thus improving the performance of your web
application. In this article you will learn the basics of using Microsoft Ajax
Minifier tool and certain programming recommendations to get most out of the
minification process.
Understanding Minification
Developers are often advised to write clear and readable
code. The variable names you use and the comments you place in your code
greatly affect the readability of your code. No doubt, as a good programming
practice you should adhere to this principle. However, these standards are of
little use to compilers, parsers and code execution engines. Consider the
following JavaScript function for example,
//The following function converts a given temperature value //from Fahrenheit to Celsius function ConvertToCelsius(value) { var newValue; newValue = (value * 1.8) + 32; return newValue; }
The ConvertToCelsius function shown above converts a given
temperature value from Fahrenheit to Celsius. The function name, variable names
used within the function, comments, etc., makes the code readable and easily
understandable. Now consider the following piece of code:
function f(b){var a;a=b*1.8+32;return a}
The function f, shown above, does exactly the same thing as
the ConvertToCelsius() function but if you compare the number of bytes in both versions,
obviously the second version is highly compact. This means the later version
will be more quickly downloaded to the client machine than the former one.
Microsoft Ajax Minifier tool works on the same principle. It
cleverly compacts your JavaScript code by applying several minification
techniques such as removing comments, renaming variables and functions and removing
white spaces (and there are many others).
Using Microsoft Ajax Minifier Command Line Tool
Microsoft Ajax Minifier is a command line tool named
AjaxMin.exe. The AjaxMin.exe supports several command line switches out of
which the following can be used for basic minification.
ajaxmin.exe <source_file> -o <destination_file> -clobber:<true/false>
In the above syntax, source_file is the path and name of the
source JavaScript file that you wish to minify. The -o switch specifies the
destination_file, B i.e. the path and name of the output file after
minification. By default the destination_file will not be overwritten if
already present. The -clobber switch allows you to control this behavior. If
you set the -clobber switch to true, the destination_file will be overwritten.
A complete list of available command line options can be
seen by /? switch.
Minifying a Sample JavaScript File
Now that you know what minification is, let’s create a
sample JavaScript file and then apply minification to it. Open Visual Studio and create
a new ASP.NET Website. Then add a new JScript file to the website and key-in
the following code:
//The following function converts a given temperature value //from Fahrenheit to Celsius and vice a versa //Example: Test(1,20,"C") function Test(month,temp,unit) { var months = new Array("Jan","Feb","Mar"); var newValue; var ConvertToCelsius = function(value) { return (value * 1.8) + 32; } var ConvertToFahrenheit = function(value) { return (value - 32) / 1.8; } if (unit == "C") { newValue = ConvertToCelsius(temp); } else { newValue = ConvertToFahrenheit(temp); } alert("The temperature in the month of " + months[month] + " was " + newValue); }
Now, open the Microsoft Ajax Minifier Command Prompt from
Windows Start menu (see below).
Figure 1: Microsoft Ajax Minifier Command Prompt
Issue the following command at the command prompt. Make sure
to change the path and file name of the source and the destination files
(JScript.js and JScript.min.js in the following figure).
Figure 2: Issue the following command at the command prompt
When you press enter, the Microsoft Ajax Minifier tool
compresses the source file and displays the statistics related to the
minification process. For example, the following figure shows that a source
file of 656 bytes is reduced to 205 during the process.
Figure 3: The Microsoft Ajax Minifier tool compresses the source file
You can now refer the JScript.min.js file in the
<script> tags throughout your web wite.
Now that you know how to use the minifier tool with its
basic switches, let’s see some of the main optimization techniques that it uses
on your JavaScript code.
How the Microsoft Ajax Minifier Tool Works
Here are some minification techniques that the Microsoft
Ajax Minifier tool applies to your code:
- Unnecessary white spaces, line breaks are removed.
function Test() { alert("Hello World"); }
becomes
function Test(){alert("Hello World")}
function Test() { alert("Hello World!"); }
becomes
function Test(){alert("Hello World!")}
are removed.
function Test(i) { if(i>100) { return i+10; } else { return i-10; } }
becomes
function Test(a){return a>100?a+10:a-10}
function Test() { var currentValue = 100; var myFunction = function() { currentValue = currentValue + 10; alert(currentValue); } }
becomes
function Test(){var a=100,b=function(){a=a+10;alert(a)};b()}
made so that escape characters are minimal.
var msg = "Please enter Email e.g. "john@somedomain.com"?";
becomes
var msg='Please enter Email e.g. "john@somedomain.com"?'
statement.
var var1 = "Hello"; var var2 = "World"; var var3 = "from"; var var4 = "JavaScript";
becomes
var var1="Hello",var2="World",var3="from",var4="JavaScript";
For example,
var dt = new Date();
becomes
var dt=new Date;
var months = new Array("Jan", "Feb", "Mar");
becomes
var months=["Jan","Feb","Mar"]
Detailed discussion of how Microsoft Ajax Minifier deals
with the code can found on the official ASP.NET website.
Coding for Better Minification
Though the Microsoft Ajax Minifier tool does a great amount
of work for you to generate a compact output, following some coding practices
can further increase the chance of better minification. Some of such coding
practices are discussed below.
Avoid Using Eval() Function and With Statement
The eval() function executes a piece of code supplied as a
string. For example, consider the eval() function call below:
eval("var myVar=100;alert(myVar);");
There is no way for the minifier tool to convert this string
literal into a compact form. As a result the call will not be compacted.
Similarly, using with statement also hampers the minification process.
var myVar = 100; with(window) { alert(myVar); }
Since the minifier tool won’t know whether myVar refers to
the variable or to a member of window object the entire block will not be
minified.
Try to Avoid Global Variables and Functions
Global variables and functions are never minified because
there is a chance that they are used from some other part of the website.
Consider the set of global variables and function below:
function MainFunction() { HelperFunction1(); HelperFunction2(); } function HelperFunction1() { alert("inside helper function 1"); } function HelperFunction2() { alert("inside helper function 2"); }
Here, the functions HelperFunction1() and HelperFunction2()
are used only by MainFunction() and are not used anywhere else. However, since
they are in global scope, the minifier tool will not compact them. You can
overcome this problem by modifying the code like this:
function MainFunction() { var HelperFunction1=function(){ alert("inside helper function 1"); } var HelperFunction2=function() { alert("inside helper function 2"); } HelperFunction1(); HelperFunction2(); }
Now, the minifier tool will compact both of the helper
functions to smaller names and calls to them will also be substituted
accordingly.
Use Shortcuts for Window and Document Objects
It is very common to use window and document JavaScript
objects in the code. If you refer them as "window" and
"document" at each and every place then you will be wasting bytes
every time. Instead you can use them as shown below:
var w = window; var d = document; function MainFunction() { d.getElementById("Div1"); w.setInterval(myCode, 1000); }
You can even wrap frequently used methods of document object
(such as getElementById) in a separate function like this:
function Get(id) { return d.getElementById(id); }
Then use the Get() function at all the places where you
would have used getElementById() method.
function DoTest() { alert(Get("abc").id); }
Minifying CSS Files
The Microsoft Ajax Minifier tool can also compact Cascading
Style Sheet (CSS) files. The process is very similar to what we discussed for
JavaScript files but with much less complication. You can refer to the official
documentation of the tool for its usage syntax and available switches for the
CSS files.
Running Microsoft Ajax Minifier Tool from Visual Studio
Microsoft Ajax Minifier is a command line tool. Rather than
opening the command prompt every time and then invoking the commands manually,
wouldn’t it be nice if you integrated it with Visual Studio IDE itself? Luckily
you can do so with simple steps.
Open Visual Studio and select "External Tools"
from its Tools menu.
Figure 4: Visual Studio: External Tools
This will open a dialog as shown below:
Figure 5: Visual Studio External Tools Dialog Box
Specify the tool title as "Microsoft Ajax Minifier."
Set Command to point to ajaxmin.exe. Add arguments as shown below:
$(ItemFileName)$(ItemExt) -out $(ItemFileName).min$(ItemExt) -clobber
The $(ItemFileName) represents the file name of the
currently opened file in the Visual Studio IDE. The $(ItemExt) represents its
extension. You can also pick these arguments from the arguments menu. Set
initial directory to $(ItemDir) i.e. the same folder as the opened file.
Finally. check the "Use Output Window" checkbox so that output
messages will be displayed there and click on the OK button. The Microsoft Ajax
Minifier tool will now be displayed on the Tools menu.
Figure 6: The Microsoft Ajax Minifier Tool
Open any JavaScript file and run the tool on it. A sample
message emitted by the tool as seen in the Output Windows is shown below:
Figure 7: Microsoft Ajax Minifier Tool Output Window
In order to see the minified file you will need to refresh
the website in the Solution Explorer.
Summary
Microsoft Ajax Minifier is a tool to produce minified
versions of JavaScript and CSS files. In this article we saw the basic usage of
Microsoft Ajax Minifier tool for minifying JavaScript files. We also discussed
certain programming practices for achieving better minification. The minified
JavaScript files will take much less time to download on the client side thus
improving the overall performance of your website.
About the Author:
Bipin Joshi is a blogger and writes about apparently
unrelated topics – Yoga & technology! A former Software Consultant by
profession, Bipin is programming since 1995 and is working with .NET framework
ever since its inception. He has authored or co-authored half a dozen books and
numerous articles on .NET technologies. He has also penned a few books on Yoga.
He was a well known technology author, trainer and an active member of
Microsoft developer community before he decided to take a backseat from the
mainstream IT circle and dedicate himself completely to spiritual path. Having
embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.