Automatically minify and combine JavaScript in Visual Studio
AJAX, JavaScript, Performance By Dave Ward on May 20th, 2009As you begin developing more complex client-side functionality, managing the size and shape of your JavaScript includes becomes a key concern. It’s all too easy to accidentally end up with hundreds of kilobytes of JavaScript spread across many separate HTTP requests, significantly slowing down your initial page loads.
To combat this, it’s important to combine and compress your JavaScript. While there are useful standalone tools and HttpHandler based solutions to the problem already, none of them work quite how I prefer. Instead, I’m going to show you my dead-simple method for automatically compressing and combining script includes.
To accomplish that in this post, we will select a compression utility, learn how to use it at the command line, explore a useful automation feature in Visual Studio, and apply that to keep scripts combined and compressed with no ongoing effort.
Selecting a JavaScript compression tool
The first thing we’ll need is a utility to compress our JavaScript. There are many utilities available, ranging from YUI Compressor to Dean Edwards’ Packer, each with its own strengths and weaknesses.
YUI Compressor is powerful, but requires a Java runtime be available during the build process. Packer is popular for its Base62 encoding mode, however that form of compression carries a non-trivial performance tax on the client-side.
In terms of simplicity, it’s hard to beat Douglas Crockford’s JSMin. It requires no command line options, no runtimes or frameworks, and accepts input directly from standard input (which will be useful for us later).
One common concern about JSMin is that it outputs less compact code than YUI Compressor and Packer on their most aggressive settings. However, this is a bit of a red herring. When gzipped, the result of all three boil down to almost exactly the same size across the wire. Since you should always serve your JavaScript with gzip compression at the HTTP level, this initial “disadvantage” is moot.
Using JSMin from the command line
Using JSMin is very straightforward. For example, say we have the following, well-commented JavaScript and want to minify it:
// how many times shall we loop? var foo = 10; // what message should we use? var bar = 'Encosia'; // annoy our user with O(foo) alerts! for (var i = 0; i < foo; i++) { alert(bar); }
Assuming that JavaScript is in a file called AlertLoop.js, this command line usage of JSMin will minify it and output it to the console:
jsmin < AlertLoop.js

What this does is run jsmin and feed the contents of AlertLoop.js into standard input. It’s the same as if you had run jsmin and then typed all that JavaScript on the command line.
Similarly, this usage does the trick if you want to redirect that output to a file:
jsmin < AlertLoop.js > AlertLoop.min.js
The minified output is less than half the size of the original. Not bad!
Note: If you’re wondering about the upper ASCII characters preceding the minified script, they’re nothing to be concerned about. Because I had created AlertLoop.js in Visual Studio, it was saved as UTF-8 by default and those characters are the UTF BOM (thanks to Oleg, Sugendran, and Bart for clarification).
Set up project directories
Before we get to the next steps, we need to define a structure for our project. The one shown to the right works for simple projects.
Within the website project, the important takeaway is that the JavaScript files to be compressed are all in the same directory and named with a *.debug.js pattern.
Outside of the website, notice the “tools” directory which contains a copy of JSMin. I think we can all agree that executables should not be included within a website project if possible. That would just be begging for trouble.
However, I do suggest including an external tools directory and JSMin executable in your project’s source control. You never want to create a scenario where someone can’t perform a checkout and then a successful build immediately afterward.
Automation: Visual Studio earns its keep
To automate script compression as part of the build process, I suggest using a build event. There are perfectly legitimate alternatives, but I prefer having a tangible file sitting on disk and having that compression process automated. So, “building” the minified JavaScript include(s) as part of the build process makes the most sense to me.
Build events may sound complicated, but they aren’t at all. Build events are simply a mechanism for executing command line code before and/or after your project is compiled.
For our purposes, a post-build event is perfect. Additionally, we can specify that it should only run the build event if the project builds successfully. That way we avoid wasting unnecessary time on minifying the JavaScript when there are build errors.
Setting up a build event in Visual Studio
To add build events, right-click on your project and choose properties. In the properties page that opens, click on the “Build Events” tab to the left. You’ll be presented with something similar to this:

Note: If you’re using Visual Basic, there will be no build events tab in the project properties. Instead, look for a build events button on the “Build” tab, which allows access the same functionality.
You can type commands directly in the post-build field if you want, but clicking the “Edit Post-build” button provides a better editing interface:

The interface’s macro list is especially useful. In particular, the ProjectDir macro will be handy for what we’re doing. $(ProjectDir) placed anywhere in a build event will be replaced with the actual project path, including a trailing backslash.
For example, we can use it to execute JSMin.exe in the hierarchy described above:
$(ProjectDir)..\tools\jsmin.exe
Or, reference that same project’s js directory:
$(ProjectDir)js\
Putting it all together: Minify a single file
Now that we’ve covered how to use JSMin at the command line and how to execute command line scripts as part of Visual Studio builds, putting it all together is easy.
For example, to minify default.debug.js, this post-build event will do the trick:
"$(ProjectDir)..\tools\jsmin" < "$(ProjectDir)js\default.debug.js" > "$(ProjectDir)js\default.min.js"
(The line breaks are for readability here. The command in your actual build event must not contain them, or it will be interpreted as separate commands and fail.)
The quotes are important, in case $(ProjectDir) happens to include directories with spaces in their names. Since you never know where this project may eventually be built at, it’s best to always use the quotes.
*Really* putting it together: Combine files
I did promise more than just compression in the post’s title. Combining scripts is just as important as compression, if not more so. Since JSMin takes its input from stdin, it’s easy to roll scripts together for minification into a single result:
type "$(ProjectDir)js\*.debug.js" | "$(ProjectDir)..\tools\jsmin" > "$(ProjectDir)js\script-bundle.min.js"
This build event would combine all of our *.debug.js scripts, minify the combined script bundle, and then output it in a new file named script-bundle.min.js.
This is great if you want to combine your most commonly used jQuery plugins into a single payload, for example. A reduction in HTTP requests usually provides a nice improvement in performance. This is especially true when you’re dealing with JavaScript, because the browser blocks while script references load.
Dealing with dependencies
Cross-dependencies between scripts is one issue that requires extra consideration when combining. Just the same as ordering script includes incorrectly, bundling scripts together in the wrong order may cause them to fail.
One relatively easy way to handle this is to give your scripts prefixes to force the correct order. For example, the source sample below includes this set of JavaScript files:
default.debug.js jQuery-1.3.2.debug.js jQuery-jtemplates.debug.js
Combining these and referencing the result will fail, because default.debug.js is sorted ahead both jQuery and the plugin by default. Since default.debug.js depends on both of those, this is a big problem. To fix this, rename the files with prefixes:
01-jQuery.debug.js
05-jQuery-jtemplates.debug.js
10-default.debug.jsNow it will work perfectly.
Any system of alphanumeric prefixes will work, but be sure to pad numbers with leading zeroes if you use a numeric system. Otherwise, the default sort ordering may catch you off guard (e.g. 2-file.js sorts ahead of 11-file.js through 19-file.js).
To debug, or not to debug
Now that we have the minification process under control, one final issue to address is how to keep this from complicating our development workflow.
While editing these scripts, we certainly don’t want to be forced to recompile every time we make a change to the JavaScript. After all, one of the nice things about JavaScript is that it doesn’t require precompilation. Even worse, using a JavaScript debugger against minified files is a nightmare I wouldn’t recommend to anyone.
The easiest way I know of to ensure that the correct scripts are emitted for both scenarios is to check the IsDebuggingEnabled property of the HttpContext:
<head> <% if (HttpContext.Current.IsDebuggingEnabled) { %> <script type="text/javascript" src="js/01-jquery-1.3.2.debug.js"></script> <script type="text/javascript" src="js/05-jquery-jtemplates.debug.js"></script> <script type="text/javascript" src="js/10-default.debug.js"></script> <% } else { %> <script type="text/javascript" src="js/js-bundle.min.js"></script> <% } %> </head>
When the web.config’s compilation mode is set to debug, the *.debug.js versions of the files are referenced, and the auto-minified bundle otherwise. Now we have the best of both worlds.
Conclusion
I hope you’ll find that this technique is a good compromise between the tedium of using manual minification tools and the overwrought complexity of setting up some of the more “enterprisey” automation solutions.
One not-so-obvious benefit that I’ve noticed stems from minification’s automatic comment stripping. Without worry about your comments burdening the size of the client-side payload or being distributed across the Internet, you’re more likely to comment your JavaScript well. Dealing with a dynamic language, sans-compiler, I find that comments are often crucial to maintainability.
This is one of those problems with quite a few perfectly legitimate solutions. What do you think of this solution? How do you normally handle this?
Get the source
For demonstration, I took my jQuery client-side repeater example and applied this technique. Having several JavaScript includes (one that’s full of comments), it’s a perfect candidate for combining and compression.
One particular thing to notice in this example is the use of numeric prefixes to order the JavaScript includes, as mentioned earlier. This naming scheme is crucial when dealing with interdependent scripts. If the scripts are combined in the wrong order, your functionality will break just the same as if you had used script reference tags in the wrong order.
Possibly related posts
What do you think? Your comments are welcome.
I appreciate all of your comments, questions, and other feedback, but please try to stay on topic. If you have a question unrelated to this post, I recommend posting on the ASP.NET forums or Stack Overflow instead.
If you're replying to an existing comment, please use the threading feature. To do this, click the "Reply to this comment" link underneath the comment you're replying to.
9 Mentions Elsewhere
- DotNetShoutout
- DotNetBurner - Visual Studio
- 9eFish
- Enlaces de Mayo: ASP.NET, AJAX, ASP.NET MVC, Visual Studio « Thinking in .NET
- New project, new language, new MVC template, hi there again C#! « Mitch Labrador's Tech Blog
- NewsPeeps
- Performance: Automatically minify java script files with Visual Studio. - Yevgeni Frolov
- links for 2009-10-28 - sashidhar.com
- How to minimize and combine your JavaScript on Compile using Visual Studio « Mitch Labrador's Tech Blog


Thank you!!!! I have been doing this manually since I started getting into jQuery and other client-side richness. Just never got around to figuring out the bits to automate this.
Great post
Great article..
One small correction though, there is a .NET version of the YUI compressor (http://www.codeplex.com/YUICompressor), it even integrates as a build step..
Cheers,
Erik
I’m with Erik, YUI Compressor for .Net is already built and works great…
There’s definitely nothing wrong with using that if you prefer it. For my use, I felt that it required more effort than was necessary (compared to the build event).
Dave,
You original file is saved in UTF-8 encoding – open it in notepad and save it as ANSI – they’ll be gone.
Or in Visual Studio you can go “File->Save As”, then click the arrow next to “Save” and choose “Save with Encoding” which will let you save it as a Windows 1252 file.
Yes, it’s the UTF BOM. It’s perfectly legal in a UTF-8 file, no need to remove it by degading the Unicode file to a smaller ranged text encoding.
Thanks for the clarification, guys.
As Sugendran suggests you can use “File-Save As” and “Save with Encoding”. But if you scroll to the bottom there is a codepage “Unicode (UTF-8 without signature) Codepage 65001″ – which saves the file in UTF-8 without any BOM.
I’m using a similar approach with the yuicompressor. But I first combine the JS files into a single file and compress that file.
Excellent article. And could not be more timely – with everyone getting so heavy into js these days!
How do it handle the ASP.NET AJAX commenting-for-intellisense format? I’d presume that it has no problems, but can anyone confirm?
The VSDOC format, like this?
/// <returns type="jQuery" />Because those begin with //, JSMin handles them the same as any other comment.
Really helpful info. One question though…
If I understand this correctly, you will need to do a build every time you change your javascript in order to update your minified file. Do you have any shortcuts or alternatives to avoiding that while developing? Obviously, you could point to your debug version while developing and then try to remember to switch to point to your minified version before going live. Seems less than ideal though. Any thoughts?
One good way to deal with that is to check the debug state of the app and render different script includes accordingly. For example, this is how you could modify the source sample to do that:
Thanks, Dave. I was considering a separate test/prod flag I use for other things. This looks like a more elegant solution that eliminates that dependency.
Wonderful article, but i would add in the main article the comment about
etc…
for me it was the missing part that would have led me to not apply this tecnique.
Maybe is just me
Tks again,
Fabrizio
ehm, i used tags and the editor ate them.
i was speaking about the
% if (HttpContext.Current.IsDebuggingEnabled) { %
part
Thanks for the feedback, Fabrizio. I think you’re right that it deserves a section in the article. I’m going to add that in.
Dave, excellent post. I arrived at your site about 1 year ago looking for this post. :)
Better late than never, I suppose!
Thank you Dave for the article. I have one question that is not exactly related to this but it will be if I need to use this. Most of the times I write javascript in the aspx page itself because we can access controls without passing the controlid. for example, If I need to read a textbox value I do
var txtValue = $(‘#’).val(); This is useful especially if I have to read lot of controls. I would like to know how other developers would program in these situations.
Thanks,
sridhar.
sridhar,
One of my coworkers wrote a nifty solution to this problem – basically how you can implement a jQuery selector to get asp.net controls (something like (“:asp(theServerID)”) ) . That selector can then be used whether you code on the .aspx page or in .js files.
http://lanitdev.wordpress.com/2009/06/08/extending-jquery-to-select-asp-controls/
Thanks for your sharing! :)
Woot!! Go YUICompressor for .NET :) :)
I might have to see if i can also intergrate that into the build process (as explained here) instead of just intergrating it into an TFS build process (or more techinically, an MSBuild Task) :)
-PK-
Another great post dear!!
Thanks!
“To debug, or not to debug”
ScriptManager can switch between foo.js and foo.debug.js automatically. Yes, even for path based references. You just have to let it know that a debug version exists — it doesn’t assume they do for path references since normally they don’t, and checking for one would be too expensive.
asp:ScriptReference Path=”foo.js” ScriptMode=”Inherit”
‘Inherit’ means use the setting from ScriptManager, which is Auto, which means switch automatically based on the debug setting.
The open source app Packer for .NET has Packer, JSMin and CSSMin all together. I use Packer for .NET via build events as described above however it’s flexible enough to be used in a number of ways.
I should add the small disclaimer that I contributed to the project (adding CSSMin) although I did so purely because I liked the solution.
You might be interested in the little project I put together for doing this at runtime, rather than the hassle of maintaining build infra and such. The idea is that it slots into ASP.NET MVC sites with a minimum of hassle. It’s usable now, though I still have the configuration-section to finish off.
docs: http://blog.neverrunwithscissors.com/tag/include-combiner
source: http://github.com/petemounce/includecombiner
builds: http://teamcity.codebetter.com/viewLog.html?buildId=2920&tab=artifacts&buildTypeId=bt63
Gr8 Post Dave.Dave i have a web project, and on right click its not showing properties but property pages.How can i access properties ?? Pls help
As far as I know, only web application projects are able to take advantage of build events. You need the .[cs|vb]proj file (which is really a MSBuild script) to set up the events.
So what happens when you use .js files that have already been minified and you still want them as part of the bundle?
For example, blockUI.min.js.
If I rename it to .debug.js (so that it’s included in the bundle) will the minifier simply leave it as is? Will there be problems if it’s been minified by an different “mini-making” algorithm?
I guess I could go and track down all un-minified versions of the jquery plugins that I use, but that would be kinda tedious.
Any suggestions?
It shouldn’t hurt anything to re-minify them.
Is there a way to add the created minified js files to the project ?
There may be an automated way to do that, but I’m not familiar with it. I just go the “show all files” -> “include in project” route:
Is there anyway to combine multiple javascripts and call from html in 1. Sorry..I’m a newbie still cannot get from the tutorial u show here.
Yes, that’s what’s being demonstrated here. Make sure you take a look at the source download. That project does exactly what you’re after.
You make it look so easy. Thank you so much…
Cheerz
Junaid Arif
Is there a way to automatically reload the combined file? Every time I do a build it displays the message box saying that the file has been modified outside the editor.
Yes, there’s a setting in Visual Studio: Environment > Documents, “Auto-load changes, if saved”.
I have spent the whole morning reading about combining and minifying CSS and JS files. Your article sheds some light on a burning question I had of how to switch files between debug and release environments and how I can do this using a NAnt script. Tools like YSlow recommend setting expire headers on your CSS and JS files and using a version number on the filename to ensure any changes get re-cached.
Is there a way to achieve this automatic versioning within the source pages?
Dave,
Can you please tell me, how can we do the same for .aspx files which has js functions included in it
I don’t know of an easy way to automate that.
If possible, you should refactor those inline scripts out into an include file. The caching gain from that will be greater than the gain from minification (and then you can easily minify it too).
If you want to use YuiCompressor in the same way that JSMin is used here I wrote an exe to do it.
Important addendum to my last post:
You’ll need to use ‘echo’ instead of ‘type’ in the build event to avoid a non existent pipe error.
I wrote a simple batch file to compress multiple files with YUI Compressor.
All you need to do is call..
multicompress.bat output.min.js input1.js input2.js input3.js input4.js … input9.js
of course you need to modify the batch file to suite your paths.
compress.bat
–
@echo off
“C:\Program Files (x86)\Java\jre6\bin\java.exe” -jar “C:\Program Files\yuicompressor-2.4.2\build\yuicompressor-2.4.2.jar” %1 %2 %3 %4 %5 %6 %7 %8 %9
–
multicompress.bat
–
@echo off
if not !%1==! del %1
if not !%2==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %2 >> %1
if not !%3==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %3 >> %1
if not !%4==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %4 >> %1
if not !%5==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %5 >> %1
if not !%6==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %6 >> %1
if not !%7==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %7 >> %1
if not !%8==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %8 >> %1
if not !%9==! call “C:\Program Files\yuicompressor-2.4.2\build\compress.bat” %9 >> %1
–
I have spent the last 2 days making a research about automating js/css minification/combining. The best solution I have found is by using this MSBuild tool: http://yuicompressor.codeplex.com/. This tool relies on a technique that is very similar to the one described in this article. The advantage is that everything is more automated, hence easier & faster for us, developers.