Monthly Archives: May 2009

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)..toolsjsmin.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)..toolsjsmin" <
"$(ProjectDir)jsdefault.debug.js" >
"$(ProjectDir)jsdefault.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)..toolsjsmin" >
"$(ProjectDir)jsscript-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:

jQuery-1.3.2.debug.js
jQuery-jtemplates.debug.js
default.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 if you use a numeric system, be sure to pad the numbers with leading zeroes. 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

Remindd Sends Email and SMS Reminders [Reminders]

There's a reason "Out of sight, out of mind" is such a common phrase—people forget things. Enter web site Remindd, a super simple solution to remembering events and appointments that should not be forgotten.

Once you've created an account, using the site is straightforward. Enter your reminder name, set a date and time for your reminder, and you're all set. You'll receive an alert via email—and SMS, if selected—five minutes before the time you chose. If you don't enter a time, your reminder will arrive at 12 AM. Be sure to set your time zone; the default is Eastern time.

Remindd sends SMS reminders through Zeep Mobile. SMS is a free option for the US only, although your standard carrier charges apply. Remindd isn’t the sole contender in the reminder market (we love Google Calendar for setting events and reminders), but it’s dead simple and works as it should.





Zilla PDF to TXT Converter Plain-Texts Your PDF Files in Bulk [Downloads]

Windows only: We’ve covered a variety of tools for converting PDF files, but if you need to bulk convert a folder full of them, Zilla PDF to TXT Converter gets the job done quickly.

If you only need to extract the text from a document or two, some of the solutions we’ve covered should more than suffice, such as emailing the PDF to Adobe’s automatic converter or using PDF-to-Word-Converter.

If you have lots of PDF files you need to extract text from, Zilla PDF to TXT Converter makes batch extraction a breeze. The freeware version is limited, as the name would suggest, to converting PDF files to plain text. You can specify the page range and whether or not to acknowledge page breaks on a file by file basis. The commercial version, PDFZilla, is $29.99 and offers batch conversion of PDF to Word, RTF, TXT, and HTML among others formats. Zilla PDF to TXT Converter is freeware, Windows only.





Netflix Streaming Arrives in Windows Media Center [Windows Media Center]

Starting today (or at least very soon), Windows Media Center users on Vista systems can stream Netflix Watch Now videos, and manage their DVD and streaming queues, straight from the TV + Movies section.

Microsoft’s announcement came late yesterday, and some in-house blogs are reporting the feature as “starting today,” but we lack a Vista system and Netflix Unlimited subscription to test it out at the moment. When it does arrive, however, users running Windows Vista Home Premium or Ultimate can fire up Media Center, head to the TV + Movies section, and should see a new Netflix option there.

Here’s how the selection and queue management should look. Search, recommendations and ratings are available from the Media Center view, and any remote that works with Media Center should be able to operate the Netflix streaming controls while it’s playing. The plug-in is Silverlight based, and requires a Netflix subscription, of course.

Running Media Center on a lower-tier Vista system, or want that same kind of Netflix streaming on your TV-connected PC? Try the myNetflix plug-in, or make the leap to Boxee or XBMC. Mac users should also check out Plex’s latest upgrade.

Here’s Microsoft’s video preview of Netflix streaming:

Thanks, Ognjen!





SuperCook Turns Your Kitchen Contents into Yummy Recipes [Recipes]

It’s cheaper and healthier to eat in, but all too easy to look in the fridge and think you have nothing to make. SuperCook tells you what you can make with what you have.
We’ve covered this…

Video: Getting Started with ASP.NET MVC 1.0

I had the opportunity to speak at the Best of Mix 09 Phoenix event with Tim Heuer and Rob Bagby and had a lot of fun hanging out with everyone.  I was the last talk and due to time constraints didn’t get a chance to cover everything I had hoped to cover, but all of the important topics were discussed. 

The projection screen doesn’t show up too well in the video unfortunately, but all of the slides and sample code can be downloaded here for those that may be interested in following along. The talk covers the fundamentals of ASP.NET MVC, discusses some great features the framework offers and describes how jQuery and even Silverlight can be integrated.  The downloadable code samples demonstrate all of the features discussed in the video.

Update: Just realized the last part of the video gets out of sync with the audio.  Re-encoding and will post the updated within the next hour or so.

Getting Started with ASP.NET MVC 1.0 

Click here to view in Windows Media Player (right-click and you can save the file)

 

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Video: Getting Started with ASP.NET MVC 1.0

I had the opportunity to speak at the Best of Mix 09 Phoenix event with Tim Heuer and Rob Bagby and had a lot of fun hanging out with everyone.  I was the last talk and due to time constraints didn’t get a chance to cover everything I had hoped to cover, but all of the important topics were discussed. 

The projection screen doesn’t show up too well in the video unfortunately, but all of the slides and sample code can be downloaded here for those that may be interested in following along. The talk covers the fundamentals of ASP.NET MVC, discusses some great features the framework offers and describes how jQuery and even Silverlight can be integrated.  The downloadable code samples demonstrate all of the features discussed in the video.

Getting Started with ASP.NET MVC 1.0 

Click here to view in Windows Media Player (right-click and you can save the file)

Logo

For more information about onsite, online and video training, mentoring and consulting solutions for .NET, SharePoint or Silverlight please visit www.thewahlingroup.com/.

Yweather Puts the Weather On Your OS X Desktop [Ubergeek]

Mac OS X only: Reader Daniel used his ubergeeky perl skills combined with GeekTool and created a more powerful way to display the current weather conditions on his desktop.

Unlike the previous weather-on-the-desktop method we’ve covered, Daniel's script extracts the current weather information from Yahoo's feeds, caches it locally, and allows you to use each piece of data separately—it even grabs the current weather image and caches it locally so you can include it on your desktop.

Daniel explained how his script works, and how he includes the information on his desktop:

I wrote a a perl script that pulls the xml from the rss feed and caches it locally and extracts the information from the local version. A parameter is included to update the local cache. In addition it also pulls the images from the main yahoo weather page that represents the weather, not the ones in the rss feed and caches them locally.

The scripts I use to display my weather in geektool are as follows, for the forecast I use 4 scripts:

echo `yweather -fd1` " - " `yweather -ft1`
echo "H: " `yweather -fh1` " L: " `yweather -fl1`
echo `yweather -fd2` " - " `yweather -ft2`
echo "H: " `yweather -fh2` " L: " `yweather -fl2`

The current temperature and description:

yweather -ct
yweather -cw

And I have the update command set to run every 30 minutes:

yweather --update && yweather --copyimage

You can grab the script for yourself at the link below, or check out how to put news on your desktop with GeekTool. If that’s not enough, learn how to monitor your Mac and more, or even add a desktop calendar to your wallpaper. Great work, Daniel!

Got your own ubergeeky, hacked together, and totally awesome productivity tricks? We’d love to hear about them! Send an email to tips [at] lifehacker.com with “ubergeek” in the subject line, and we may just feature them here.

Update: Daniel posted a new bug-fixed version of the script over at Google Code, which should be the permanent location for the script from now on. Thanks!

Yweather perl script [Google Code]





Backup Maker Offers Dead Simple Backup Creation [Downloads]

Windows only: Backup Maker offers extremely simple wizard-driven backup to a variety of local media and remote hosts.

Whether you’d like to backup to another disk, burn the files to a CD, or transfer them to a remote FTP site, Backup Maker has a variety of solutions to backup your data. It handles both the backup and the restoration of files and has an easy to use wizard for creation of scheduled backup routines. You can specify whether files are to be completely overwritten each time or only incrementally with files being replaced and added as they are altered. Restoration is just as simple with point and click dumping of your data from the backup to the previous location. The software is free, although after batch backups a nag screen does pop up suggesting potential upgrades to other software offered by the company. For other backup solutions, minus the pop up screen, make sure to check out the Hive Five for backup tools. Backup Maker is freeware, Windows only.





Tear Mender Patches Rips in a Jiffy [Stuff We Like]

If you (or your kids) live a rough-and-tumble lifestyle, Tear Mender makes instant patches on fabric and leather for a quick and effective fix.

How well does it work? According to weblog Cool Tools:

Better than iron patches? Yes. Holds much better. Never comes off and easy to add additional repairs. If you're careful, you can make "neat" patches, or you can make very strong patches that aren't so pretty. You can wash Tear Mender—over and over and over.

We haven’t had the opportunity to use Tear Mender yet, but for $8 at Amazon, it sounds like a great addition to your household DIY kit. (Check out the instructional videos on the Tear Mender homepage for more usage specifics.) If you’ve had a chance to use it in the past, share your experience in the comments.

Tear Mender [Amazon via Cool Tools]





WP Like Button Plugin by Free WordPress Templates