Welcome!

Blog Feed Post

Automatically minify and combine JavaScript in Visual Studio

As 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

jsmin-stdin

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

jsmin-to-file

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

project-layoutBefore 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:

project-properties

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:

post-build-events

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.js

Now 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.

Download Source: jsmin-build.zip

###

Originally posted at Encosia. If you're reading this elsewhere, come on over and see the original.

Automatically minify and combine JavaScript in Visual Studio

Read the original blog entry...

More Stories By Dave Ward

Dave Ward wrote his first computer program in 1981, using good ‘ol Microsoft Color BASIC and cassette tapes for data storage. Over the years since then, he has had the opportunity to work on projects ranging from simple DOS applications to global telecommunications networks spanning multiple platforms.

Latest Stories
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
As you move to the cloud, your network should be efficient, secure, and easy to manage. An enterprise adopting a hybrid or public cloud needs systems and tools that provide: Agility: ability to deliver applications and services faster, even in complex hybrid environments Easier manageability: enable reliable connectivity with complete oversight as the data center network evolves Greater efficiency: eliminate wasted effort while reducing errors and optimize asset utilization Security: imple...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Companies are harnessing data in ways we once associated with science fiction. Analysts have access to a plethora of visualization and reporting tools, but considering the vast amount of data businesses collect and limitations of CPUs, end users are forced to design their structures and systems with limitations. Until now. As the cloud toolkit to analyze data has evolved, GPUs have stepped in to massively parallel SQL, visualization and machine learning.
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Modern software design has fundamentally changed how we manage applications, causing many to turn to containers as the new virtual machine for resource management. As container adoption grows beyond stateless applications to stateful workloads, the need for persistent storage is foundational - something customers routinely cite as a top pain point. In his session at @DevOpsSummit at 21st Cloud Expo, Bill Borsari, Head of Systems Engineering at Datera, explored how organizations can reap the bene...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Kubernetes is an open source system for automating deployment, scaling, and management of containerized applications. Kubernetes was originally built by Google, leveraging years of experience with managing container workloads, and is now a Cloud Native Compute Foundation (CNCF) project. Kubernetes has been widely adopted by the community, supported on all major public and private cloud providers, and is gaining rapid adoption in enterprises. However, Kubernetes may seem intimidating and complex ...
In his session at 21st Cloud Expo, Michael Burley, a Senior Business Development Executive in IT Services at NetApp, described how NetApp designed a three-year program of work to migrate 25PB of a major telco's enterprise data to a new STaaS platform, and then secured a long-term contract to manage and operate the platform. This significant program blended the best of NetApp’s solutions and services capabilities to enable this telco’s successful adoption of private cloud storage and launching ...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
In his general session at 21st Cloud Expo, Greg Dumas, Calligo’s Vice President and G.M. of US operations, discussed the new Global Data Protection Regulation and how Calligo can help business stay compliant in digitally globalized world. Greg Dumas is Calligo's Vice President and G.M. of US operations. Calligo is an established service provider that provides an innovative platform for trusted cloud solutions. Calligo’s customers are typically most concerned about GDPR compliance, application p...
Digital transformation is about embracing digital technologies into a company's culture to better connect with its customers, automate processes, create better tools, enter new markets, etc. Such a transformation requires continuous orchestration across teams and an environment based on open collaboration and daily experiments. In his session at 21st Cloud Expo, Alex Casalboni, Technical (Cloud) Evangelist at Cloud Academy, explored and discussed the most urgent unsolved challenges to achieve f...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.