在MVC脚本包中使用CDN。我错过了什么?

时间:2013-03-14 04:45:04

标签: c# asp.net-mvc cdn

我正在尝试使用CDN加载jquery。我已阅读this文章,这看起来应该非常简单。

我的脚本包定义如下。

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"));

我将其包含在页面中如下:

<!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>

但是当我看到firebug时,似乎从localhost加载了jquery。 firebug inspection

我已尝试使用realease和debug版本。 我错过了什么?我认为这应该是非常简单的。感谢。

3 个答案:

答案 0 :(得分:44)

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

答案 1 :(得分: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

答案 2 :(得分:8)

确保您未处于调试模式。

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

设置BundleTable.EnableOptimizations = true; //如果要使用调试模式

  

jQuery将在发布模式下从CDN请求   调试版本的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> 
相关问题