详解Asp.Net MVC的Bundle捆绑

2019-12-30 18:33:34丽君

但是Bundle类也提供了IncludeDirectory方法,可以添加指定目录下的指定文件。


//添加Content/themes/base目录下的所有css文件
bundles.Add(new StyleBundle("~/Content/css"").IncludeDirectory("~/Content/themes/base", "*.css"));

使用通配符要注意:

使用通配符添加资源时。这些资源文件是按照名称来排序的。

2. 启用Bundle

在Global.asax的Appliaction_Start方法中调用之前的定义的方法,BundleConfig.RegisterBundles(BundleTable.Bundles)
启用Bundle。


public class MvcApplication : System.Web.HttpApplication
{
 protected void Application_Start()
 {
  BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
}

3. 使用Bundle

如果我们需要在页面中使用这些资源时。可以通过Styles和Scripts来引入。如果要使用捆绑的Style,可以在页面中添加@Styles.Render("~/Content/css")。如果要使用捆绑的Script,可以在页面中添加@Script.Render("~/bundles/jquery")

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>@ViewBag.Title - 我的 ASP.NET 应用程序</title>
 //引入样式捆绑
 @Styles.Render("~/Content/css") 
</head>
<body> 
 <div class="container body-content">
  @RenderBody()
  <hr />
  <footer>
   <p>© @DateTime.Now.Year - 我的 ASP.NET 应用程序</p>
  </footer>
 </div>
 //引入js捆绑
 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>
</html>

可以把CSS样式文件置顶,JavaScript文件置底,来优化网页。但是modernizr.js文件要放在页面顶部,因为有些样式文件需要。

使用CDN

Bundle对CDN也提供了很好的支持。


public static void RegisterBundles(BundleCollection bundles)
{
 //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
 //   "~/Scripts/jquery-{version}.js"));

 bundles.UseCdn = true; //启用cdn
 //添加地址
 var jqueryCdnPath = "http://www.easck.com/ajax/jQuery/jquery-1.7.1.min.js";
 bundles.Add(new ScriptBundle("~/bundles/jquery",jqueryCdnPath).Include("~/Scripts/jquery-{version}.js"));
}

在使用CDN时,要应对没有获取到资源的情况。


@Scripts.Render("~/bundles/jquery")
  <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>