Thursday, November 28, 2013

ASP.NET MVC - Organizing your BundleConfig.cs

Here's how I organize my BundleConfig.cs in my ASP.NET MVC projects

BundleConfig.cs http://pastie.org/8514126
_Layout.cshtml http://pastie.org/8514131

First we have two static classes, "JavaScript" and "CSS".

These have both static sub-classes, "Bundles" and "CDN". The "Bundles" class contains const strings which are both keys for the bundle and the virtual path to the code location. The "CDN" class contains URLs.

public static class BundleConfig
{
    public static class JavaScript
    {
        public static class Bundles
        {
        }

        public static class Cdn
        {
        }
    }
    public static class Css{...}
}

For JavaScript, In the "Bundles" class, I keep my JavaScript in the folder "~/Scripts/" where jquery-2.0.3.js resides. Thus, the virtual path becomes "~/Scripts/jquery-2.0.3.js" and this text is contained in the string "Jquery".

public static class Bundles
{
    private const string PathBase = "~/Scripts/";
    public const string Jquery = PathBase + "jquery-2.0.3.js";
}

Below is the static class "CDN" which has a similar structure, which are just URLs that matches the above JavaScript classes. A CDN is very useful since it offloads loading time from your server, and data from the CDN can also run in parallel with loading the response from your server.

public static class Cdn
{
    public const string Jquery = "http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js";
}

The "CSS" class functions similarly, with both a Bundle and a CDN class.

With this setup, registering the bundles becomes very easy and clean.

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle(JavaScript.Bundles.Jquery, JavaScript.Cdn.Jquery).Include(JavaScript.Bundles.Jquery));
}

Likewise, including the Bundle is also clean
@Scripts.Render(BundleConfig.JavaScript.Bundles.Jquery)

Some additional tips:

Always place your javascript at the end of your <body> element, as it will block the rendering of the site if you place it above the content.

No comments:

Post a Comment