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:

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.

  4 Responses to “Debug JavaScript in MVC”

  1. Nice. We use something similar to append a version querystring to ensure users are forced to download latest js to match our build number.

    A method per js file is going to get pretty annoying? If your files followed some convention you could push the Debugger test into the Scripts method.

    • We use the file modified time stamp as a query string so that the caching works the same in development automatically without needing to do anything special during the build.
      You are likely to want to be able to reference scripts on a CDN (for perf). So you could probably store a dictionary of pairs and refactor out the logic that selects the JavaScript type to use. I would do this when I have a large number of scripts, but I would probably focus on solving the perf issues that come with that many scripts first. :)

  2. Are you stalking me…? Again I was looking at doing the same thing just last night… Although I was trying to generalise it into 1 load scripts helper method. If only all the different libraries used the same suffix / naming standard for dev scripts…

    • That shirt is not your colour :)
      Don’t forget some scripts might not be required on some pages (you could use Areas or the single page to load what is needed) and referencing a script on a CDN might be quicker for your users.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2011 keza.net Suffusion theme by Sayontan Sinha