45

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. firebug inspection

I have tried with both realease and debug builds. What am I missing? I think this should be quite straightforward. Thanks.

4

3 回答 3

45

在模式下运行您的应用程序debug="false"或使用BundleTable.EnableOptimizations = true;

于 2013-03-14T05:45:02.887 回答
16

实际上,当使用最新版本的 ASP.NET MVC 时,您可以更短地编写 @RaviGadag 他的方法。这样您就不必自己在布局中编写回退:

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;
}

内容交付网络 (CDN) 中可用的 jquery 版本: http ://www.asp.net/ajax/cdn#jQuery_Releases_on_the_CDN_0

于 2015-05-13T09:32:54.993 回答
9

确保您未处于调试模式。

  bundles.Add(new ScriptBundle("~/bundles/jquery", "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js")

set BundleTable.EnableOptimizations = true;// 如果你想使用调试模式

在发布模式下会从 CDN 请求 jQuery,并且在调试模式下会在本地获取 jQuery 的调试版本。使用 CDN 时,您应该有一个回退机制,以防 CDN 请求失败。

如果 CDN 请求失败,那么您可以提供回调

<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> 
于 2013-03-14T05:00:18.153 回答