Reputation: 1972
I am trying to use a CDN for loading jquery. I have read this article and this seems like it should be very straightforward.
My script bundle is defined as follows.
bundles.UseCdn = true;
bundles.Add(new ScriptBundle("~/bundles/jquery", "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js").Include(
"~/Scripts/jquery-{version}.js"));
I am including it on the page as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
But when I look at firebug it seems that jquery is being loaded from localhost.
I have tried with both realease and debug builds. What am I missing? I think this should be quite straightforward. Thanks.
Upvotes: 46
Views: 70945
Reputation: 18567
Actually you can write @RaviGadag his method shorter when using a recent version of ASP.NET MVC. This way you don't have to write the fallback yourself in the Layout:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.UseCdn = true;
var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js";
var jqueryBundle = new ScriptBundle("~/bundles/jquery", jqueryCdnPath).Include("~/Scripts/jquery-{version}.min.js");
jqueryBundle.CdnFallbackExpression = "window.jQuery";
bundles.Add(jqueryBundle);
// ...
BundleTable.EnableOptimizations = true;
}
available jquery versions in the Content Delivery Network (CDN): http://www.asp.net/ajax/cdn#jQuery_Releases_on_the_CDN_0
Upvotes: 17
Reputation: 15861
make sure you are not in debug mode.
bundles.Add(new ScriptBundle("~/bundles/jquery", "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js")
set BundleTable.EnableOptimizations = true;
// if you want to use debug mode
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.
if CDN Request fail then you can provide a callback
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
var e = document.createElement('script');
e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")';
e.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(e);
}
</script>
Upvotes: 9
Reputation: 1404
Run your application in debug="false"
mode or use BundleTable.EnableOptimizations = true;
Upvotes: 46