ASP.NET MVC4 bundling CSS Some on CDN some local to server?

Ken Burkhardt picture Ken Burkhardt · Nov 9, 2012 · Viewed 7k times · Source

I am looking into the ASP.NET MVC4 System.Web.Optimization bundling and was wondering how would you go about serving up some CSS files from a CDN and others local to a server?

Is that possible?

It looks like the bundles.UseCdn = true is at the collection level and not a setting for an individual bundle.

Any guidance would be appreciated.

Answer

Justin Helgerson picture Justin Helgerson · Nov 9, 2012

The ASP.NET site has some information about this:

The following code replaces the local jQuery bundle with a CDN jQuery bundle.

public static void RegisterBundles(BundleCollection bundles)
{
    //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
    //            "~/Scripts/jquery-{version}.js"));

    bundles.UseCdn = true;   //enable CDN support

    //add link to jquery on the CDN
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
}

In the code above, jQuery will be requested from the CDN while in release mode and the debug version of jQuery will be fetched locally in debug mode. When using a CDN, you should have a fallback mechanism in case the CDN request fails. The following markup fragment from the end of the layout file shows script added to request jQuery should the CDN fail.

Personally, I don't find myself debugging code from jQuery, Knockout, or any other library. I always reference the CDN resource directly in my layout. Any scripts I need to roll myself I then bundle using the MVC framework.

My sites usually look something like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
@Scripts.Render("~/content/js/siteName")