Dharmik Bhandari
Dharmik Bhandari

Reputation: 1702

CDN path is not working in js bundling in MVC

I'm working on ASP.NET MVC4. Client has requirement to load all javascripts and css from other domains like CDN with bundling. I've used System.Web.Optimization.

below is the code.

 var bundle = new ScriptBundle("~/bundles/scripts/");
bundle.Orderer = new AsIsBundleOrderer();
bundle.EnableFileExtensionReplacements = false;
bundle.CdnPath = "http://js.cusomdomainname.com";
bundle.Include("~/Scripts/jquery-1.7.1.min.js",
                "~/Scripts/jquery.unobtrusive-ajax.min.js",
                "~/Scripts/jquery.validate.min.js",
                "~/Scripts/jquery.validate.unobtrusive.min.js");

BundleTable.Bundles.UseCdn = true;
BundleTable.EnableOptimizations = true;
BundleTable.Bundles.Add(bundle);
BundleTable.Bundles.IgnoreList.Clear();

on view

@Scripts.Render("~/bundles/scripts/")

But It's is not rendering from another domain.

What could be the problem?

Upvotes: 5

Views: 8059

Answers (2)

Brandon Cuff
Brandon Cuff

Reputation: 1478

I don't care for the way the cdnPath stuff works in bundling because you can only specify a single file path for the whole bundle. If you want to set up a simple origin-pull CDN it's much easier to do the following:

@Scripts.RenderFormat(
    "<script src='http://js.cusomdomainname.com{0}'></script>",
    "~/bundles/scripts/")

This will work if you have a bundle with lots of different files whether or not optimizations are enabled.

This also gets around the problem with the query parameter described here

Upvotes: 1

jjokela
jjokela

Reputation: 337

This example shows how to load resource from CDN in 'release' mode and locally from 'debug' mode.

var jqueryCdnPath = "//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js";
var jqueryBundle = new ScriptBundle("~/bundles/jqueryCdn", jqueryCdnPath)
                       .Include("~/Scripts/jquery-{version}.js");

BundleTable.Bundles.Add(jqueryBundle);

CdnPath refers to a resource you want to get from a CDN, and Include tells where to find that locally. You can change which one is requested from Web.config. Set <compilation debug="true"/> to use local file, and <compilation debug="false"/> to use CDN.

See this Bundling and Minification article for more information.

Upvotes: 5

Related Questions