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?
Bundling and minification can be enabled or disabled in two ways: either setting the value of the debug attribute in the compilation Element in the Web. config file or setting the enableOptimizations property on the BundleTable class. In the following example, debug is set to true in web.
What is CDN? The Content Delivery Network (CDN) is a media server where we can host a site's images, CSS, JavaScript, PDF and video files and so on. There will be two media servers, one for a HTTP request and one for a HTTPS request. Using a CDN server provides the following advantages: Cached version of files.
Include(""~/Scripts/html5shiv. js"); //fallback in debug mode. As per document: "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."
To improve the performance of the application, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With