Debug JavaScript in MVC

Most JavaScript libraries come with a minified version that is quick to load, and a debug version that lets you debug issues. In ASP.net MVC you really want to be using the debug JavaScript while developing, and the minified Javascript when your site goes into production. I thought up this handy tip that gives a good return, for little investment.

Step 1: Change your layout pages to reference your JavaScript files via a UrlHelperExtensions class.

Step 2: In the UrlHelperExtensions class write some code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static string Scripts(this UrlHelper helper, string fileName)
{
    return helper.Content("~/Content/Scripts/" + fileName);
}
public static string knockout(this UrlHelper helper)
{
    if (System.Diagnostics.Debugger.IsAttached)
        return Scripts(helper, "knockout-1.2.1.debug.js");
    return Scripts(helper, "knockout-1.2.1.js");
}
public static string CDNjquery(this UrlHelper helper)
{
    if (System.Diagnostics.Debugger.IsAttached)
       return "//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js";
    else
        return "//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js";
}

The jQuery example here is using a CDN in the hopes that the visitor already has it in their browser cache.

Now your JavaScript will load quickly and you can still debug during development.