Using the New Microsoft Ajax Minifier

Last night, Scott Guthrie announced that the ASP.net team published a free tool that enables you to improve the performance of your Ajax applications by reducing the size of its JavaScript files. The new tool is named the Microsoft Ajax Minifier.

You can read Scott Guthrie’s announcement here:

http://weblogs.asp.net/scottgu/archive/2009/10/15/announcing-microsoft-ajax-library-preview-6-and-the-microsoft-ajax-minifier.aspx

And you can download and install the free tool from the CodePlex website here:

http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=34488

In this blog entry, I explain how you can take advantage of the Microsoft Ajax from the command-line and when you are using Visual Studio.

Overview of the Microsoft Ajax Minifier

The Microsoft Ajax Minifier was created by Ron Logan (who is clearly a super-genius). The Microsoft Ajax team (I work on this team) has been using this tool internally for a number of years. For example, we use the Microsoft Ajax Minifier to minify the Microsoft Ajax Library before publishing it.

The Microsoft Ajax Minifier enables you to reduce the size of a JavaScript file by removing unnecessary content from the JavaScript file. The tool supports two modes: normal crunching and hypercrunching.

When you use normal crunching, the Microsoft Ajax Minifier strips all comments, unnecessary whitespace, curly-braces, and semicolons from a JavaScript file. Surprisingly, just removing all of this unnecessary code fluff can make a significant difference to the size of a JavaScript file.

When you use hypercrunching, the Microsoft Ajax Minifer gets more aggressive about reducing the size of a JavaScript file. In hpercrunching mode, the Microsoft Ajax Minifier shortens the names of local variables (variables in functions but not global variables) and it removes unreachable code.

For example, here’s an unminified JavaScript file:

// Adds two numbers

function addNumbers(firstNumber, secondNumber, thirdNumber)

{

var result = firstNumber + secondNumber + thirdNumber;

return result;

}

// Calculate cost

var cost = addNumbers(1, 2, 3);

And here is the same JavaScript file after it has been hypercrunched using the Microsoft Ajax Minifier:

function addNumbers(b,a,c){var d=b+a+c;return d}var cost=addNumbers(1,2,3)

It is important not to confuse minifying with compressing. Both approaches to reducing the size of a JavaScript file are important. You can configure IIS to compress JavaScript files using GZIP compression automatically. You get additional performance benefits from minifying JavaScript files before compressing them.

Using the Microsoft Ajax Minifier from the Command-Line

When you install the Microsoft Ajax Minifier, you get a convenient Microsoft Ajax Minifier Command Prompt that you can invoke from Start, Microsoft Ajax Minifier program group.

clip_image002

This command prompt adds the Microsoft Ajax Minifier to the path variable so that you can change directories and still run the Microsoft Ajax Minifier.

Use the following command to perform normal crunching:

ajaxmin inputfile.js –o outputfile.js

Use the following command to perform hypercrunching:

ajaxmin –hc inputfile.js –o outputfile.js

The Microsoft Ajax Minifier has a number of different switches that you can use to control how a file gets minified. These options are documented in the Microsoft Ajax Minifier documentation included in the Microsoft Ajax Minifier program group.

Using the Microsoft Ajax Minifier as a Visual Studio Build Task

You also can integrate the Microsoft Ajax Minifier directly into the Visual Studio build process. In that case, every time you perform a build, you can minifying all of the JavaScript files in your project automatically.

When you install the Microsoft Ajax Minifier, a new MSBuild task named ajaxmin is added to the following folder:

Program FilesMSBuildMicrosoftMicrosoftAjax

In order to use this custom build task in a Visual Studio Project, you need to modify the project file. You can modify a project file by opening the project file in Notepad. Just open Notepad and browse to your project folder and open the projectname.csproj or projectname.vbproj file.

Alternatively, you can modify your project file directly within Visual Studio by right-clicking your project name in the Solution Explorer window and selecting the menu option Unload Project. Next, you need to select the menu option Edit Project Name (see the following screenshots).

clip_image004

clip_image006

I admit that, even though I work on the ASP.NET team, I had never noticed the Unload Project, or Edit Project Name menus before. A good day is a day when you can discover a super obscure Visual Studio menu item!

After you open your project file using Notepad or Visual Studio, you need to add the following section anywhere within the project file (within the opening and closing <project> elements):

<Import Project="$(MSBuildExtensionsPath)MicrosoftMicrosoftAjaxajaxmin.tasks" />

<Target Name="AfterBuild">

<ItemGroup>

<JS Include="***.js" Exclude="***.min.js;Scripts*.js" />

</ItemGroup>

<AjaxMin SourceFiles="@(JS)" SourceExtensionPattern=".js$" TargetExtension=".min.js" />

</Target>

This section imports the AjaxMin task. It causes the task to be executed after a build. The <ItemGroup> element is used to specify the set of files to minify. In this case, all files ending in the extension .js, but not files ending in the extension .min.js are selected for minification. All the files from the Scripts folder are also excluded (So jQuery and MicrosoftAjax won’t get re-minified). Finally, the files are actually minified by invoking the task with the <AjaxMin> element.

After you make these changes, you can reload your Visual Studio project by right-clicking your project in the Solution Explorer window and selecting the Reload Project menu option.

Because we added a custom task to our project — and a custom task could do evil things like delete your entire hard drive — you get the following warning dialog:

clip_image008

Select Load project normally and your project will appear in the Solution Explorer window again.

Now here is the fun part. Now, that we have added the Microsoft Ajax Minifier task to our project file, every JavaScript file will get minified every time we perform a build. Just select the Build, Build Solution or Build, Build Project to perform the minification (or hit F5).

Be aware that minified files are not added to a project automatically after a build. After performing a build, select the menu option Project, Show All Files to see the new minified files.

clip_image010

Conclusion

The Microsoft Ajax Minifier makes it much easier to build high-performance Ajax applications. By reducing the size of your JavaScript files, you can enable the visitors to your website to download your Ajax applications much faster.

Discussion

  1. Alan says:

    How would you use the build task within a “ASP.NET Web Site” that doesn’t have a csproj file?

  2. besthdsoft2 says:

    How to rip Blu-ray Disc to all video format, for example iPod, iTouch, iPhone, Zune, PSP, PDA, Cell Phone, Apple TV, Xbox 360, AVI, Xvid, MPEG, WMV, MP4, H264 and so on? With the freeware guide, you can ripping Blu-ray DVD movie by yourself fast and easily!

    rip blu ray to mpeg, convert blu ray to psp, convert blu ray to wmv

  3. Chris says:

    Alan – you’ll need to download and install the web deployment project for visual studio add-in. However, if you’re using the express versions of visual studio, you’re out of luck, as the add-in only works with paid-for versions of visual studio.

  4. Matt says:

    “after it has been hypercrunched”

    function addNumbers(firstNumber,secondNumber,thirdNumber){var result=firstNumber+secondNumber+thirdNumber;return result}var cost=addNumbers(1,2,3);

    Shouldn’t hypercrunch mode shorten firstNumber, secondNumber etc..?

  5. Peter says:

    Shouldn’t hypercrunch mode shorten firstNumber, secondNumber etc..?

    Maybe those variable names are not that long…

  6. Praveen Prasad says:

    hi Steven, how are you doing.

    Nowadays the size and number of js files are becoming large and large, and its really tough to manage them.
    my current project is having 56 js files and its really tough to manage them.
    I think codefolding feature in js files would really decrease the pain by some amount.

    What my question is, can we expect code folding feature or something like that in js files in near future release.

  7. Germán says:

    Hi,

    Is there a way to bundle various source javascript files in my projet in just one minified hypercrunched file? This would increase performance as the browser would download all javascript code in one download but still allowing the developer to logically split the code in various source files.

    Thanks.

  8. Germán says:

    Hi!!
    I have found the solution for bundling files with msbuild here:
    blogs.msdn.com/…/475046.aspx

    So I have modified the msbuild to bundle the javascript files after minifiying.

    Thanks.












  9. Mike says:

    ajaxmin?

    Why not jsmin?

  10. Mike says:

    @ Germán

    Use the script manager to combine scripts into one request.

    @Stephen

    Is there an option to replace the original with the minified scripts in the output? Because my source html references script.js, and not script.min.js

    Or is there a task for that too?

  11. @Mike — If you want to replace the original then you have two options: (1) Generate temporary minified files, delete the originals, and rename the temporary ones. There are build tasks for deleting and copying. See msdn.microsoft.com/en-us/library/7z253716.aspx.

    The other option is to write your own build task that uses the ajaxmin.dll assembly. The current build task only has about one dozen lines of code. Creating a custom build task would not be difficult: msdn.microsoft.com/en-us/library/t9883dzc.aspx

    Hope this helps!

  12. @Matt, @Peter — My mistake, I fixed the code sample to be hypercrunched. Thanks!

  13. Brian says:

    Hello,

    If one were to have:

    debug scripts = .debug.js extension
    prod/min scripts = .js extension

    Is that easy to setup? I don’t use the .min.js extension.

    Thanks.

  14. Thanks Steph, but by applying minifying in this way we should always reference the minified .js files in web pages. This works well when the project in its final stages so after doing all the development just minify the .js files and deploy the minified files instead of the original ones. The point is what if the minifying process being add to a the asp.net pipeline so when a .js file is being requested its minified automatically at the runtime and no need to the manually minifying, changing file names ..etc? This will be also good to allow minifying the embedded .js files as web resources.

  15. Michael Stuart says:

    You guys should just make it so vs.net 2010 has an option so it can automatically do the minify for you when you build in Release mode.

  16. Matt W. says:

    Why is it called the AJAX minifier?

    1.) It clearly is written to make JavaScript responses that contain JavaScript smaller.

    2.) AJAX responses rarely include JavaScript.

    This change won’t enhance the performance of most AJAX requests or responses. It will make loading the components that can make those requests require less bandwidth.

    This is a generic JavaScript “minify” tool that can provide a performance enhancement, but it has nothing to do with AJAX other than JavaScript is the language by which we create AJAX requests. It might as well be called the “Form Validation Minifier” or the “Cookie Manipulation Minifier”.

    “JavaScript minifier” would be more appropriate.

    To respond to the “why not automatically?” question. A lot of time and effort goes into the QA of JavaScript in enterpise applications. I’d be wary of anything that were to change the source automatically. It would require a complete retest of any existing application.

  17. When writing a custom control library, the only file you should need to give people is the *.dll. I normally add the JavaScript for custom controls using the Page.ClientScript.RegisterClientScriptBlock method (after, of course, checking to make sure another instance of the control didn’t add it already). Is there a way to have the Minifier minify this code?

  18. I have downloaded the minifier from codeplex and tried them on JS files in one of my project, the tool reduced the file size by 25% in normal mode and 50% in hyper mode. Thanks

  19. Andy says:

    @Mike

    We use web deployment projects for all our web UI projects and configure our builds to only use the projects for Staging and Release builds.

    I’ve just been playing with the miniying build task to see if i can get it to keep the same .js filenames rather than .min.js so that the pages refer to the minified versions for staging and release builds.

    After a bit of playing around, it turned out it was quite simple, just change the TargetExtension to .js :

  20. Andy says:

    @Mike

    Sorry wouldn’t let me post the code but I think you’ll get what I mean 🙂

  21. zm says:

    Hi Stephen,

    does the msbuild task you provided work on 64bit Win7? I put the code on my project, it does not do anything.

    when i installed AjaxMin, setup installed it in “C:Program Files (x86)MSBuild”

    where does $(MSBuildExtensionsPath) points to ?

  22. @zm — Look in the Visual Studio Output window after performing a build to see if there are any error messages.

    You aren’t required to use $(MSBuldExtensionPath) — you could just hardcode the path “C:Program Files (x86)MSBuild” instead.

    Hope this helps!
    Stephen

  23. zm says:

    No error messages in output window. it builds successfully.

    i replaced $(MSBuldExtensionPath) with “C:Program Files (x86)MSBuild” … no go.

    This is what i have on my .csproj right after







  24. zm says:

    seems like i cant post code. 🙁

    This is what i have on my .csproj right after Project element.

    Import Project=”C:Program Files (x86)MSBuildMicrosoftMicrosoftAjaxajaxmin.tasks”

  25. @zm — That looks perfect. You should get an error in the Output window if Visual Studio can’t import the ajaxmin task (if the path is wrong). If your JavaScript files are not contained in the Scripts folder then they should be minified or you should get an error message.

    Apologies, I don’t know what else to recommend.

  26. zm says:

    do javascript files have to be in some specific folder?

    all my js files are in /Resources/Scripts folder

    No worries. currently i have YUI JS minifier setup as an external tool in VS and it does a good job. only thing i dont like is i have to select the js file first to minify it.

    being able to minify all js files at build time would have been perfect.

  27. <span style=”TEXT-DECORATION: underline”>Fake rolex watches</span>— There is no secret that

    http://www.excelwatch.com?>Rolex watches
    is one of the most beloved watches all over the world.
    <span style=”TEXT-DECORATION: underline”>Replica rolex watches</span> are exact imitation from the originals. Each piece is paid closely attention in manufacturing, and inspected carefully before it was taken out of the warehouse. Choose one of elegant and classic models, and enjoy every moment in life with our amazing timepiece of first-class quality at reasonable price. 🙂



    <span style=”TEXT-DECORATION: underline”>Fake rolex watches</span>

  28. Really help full info for me thanks a lot!!!!!!!!!!!

  29. Steve says:

    You should be able to point the command line utility to an input directory and an output directory and have it minify everything using the same filenames. Since I need to minify 141 files in a single directory it looks like I’ll need to create an XML file for it.

    Since no one has answered the first post from Alan, I assume you can’t use the build task within a ASP.NET Web Site that doesn’t have a csproj file.

    It’s a good start but needs more features and the help file needs to further explain using XML.

  30. @Steve — For a website (in contrast to a web application project) you need to create a custom build provider that performs the minification. Not super difficult, but it would take a couple of hours. Here is a blog entry that introduces build providers: weblogs.asp.net/…/424337.aspx
    Hope this helps!

  31. Phil says:

    Is it possible to have the tool compress the files and combine them into one aggregated output file? If you have a large number of .js files, having them combined for one HTTP request would be really helpful and of course provides better performance than having to get each file individually.

  32. Phil says:

    One day I’ll learn to RTFM before I post comments with dumb questions. The range of options is really impressive for what is essentially a very simple tool. Can see this being an integral part of our build process.

  33. RichB says:

    Is this the tool formerly called JSCrunch? I’d like to see a comparison with Dojo ShrinkSafe as they both work the same way – ie generate an AST using a full JavaScript engine and compress based on the AST representation.