mvc4开篇之BundleConfig(1)

新建一个mvc4默认项目,会看到以下目录

打开App_start 里面BundleConfig.cs文件

你会看到这么一段话:

有关 Bundling 的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=254725

我现在讲的东西跟上面网址所说大同小异,不同网址里面是英文版

我这里讲的一些简单点

Bundling 这个英文从字面意思来说是:捆绑意思。。。

从程序层面来说:就是将所有文件捆绑在一起,然后压缩成一个文件

Demo就不使用官方,我手动建一个,估计大家会看明白点

1、在BundleConfig.cs加入以下2段话

 bundles.Add(new StyleBundle("~/test/style").Include(
                         "~/Content/a.css",
                         "~/Content/b.css"));

 注意:~/test/style这个可以理解虚拟文件夹,实际上是不存在,但它里面包括2个文件 

~/Content/a.css 和 ~/Content/b.css

2、 在a.css加入以下内容,没有实际意义,为了测试

.a_test_style {
font-size:12px;
}

在b.css加入以下内容,没有实际意义,为了测试

.a_test_style {
font-size:12px;
}

3、在Home文件夹增加Index视图,当然对于controller也要增加 index()方法

参考一下官方调用例子 site.master里面

<%: Styles.Render("~/Content/css") %>
<%: Scripts.Render("~/bundles/modernizr") %>
<%: Styles.Render("~/Content/themes/base/css") %>

测试页面代码很简单

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>
    <%:Styles.Render("~/test/style") %>
</head>
<body>
    <div>
        <p>有钱就是任性</p>
    </div>
</body>
</html>

  

调用:<%:Styles.Render("~/test/style") %>

4、生成 运行,看到以下结果

看到2条请求(google浏览器 F12)


当然 这个效果不是我最终所要的..

5、这就要我们合并文件,有2个方法


1、在配置文件Config<compilation debug="true" targetFramework="4.0" />  将debug改为false

2、在BundleConfig.cs加上这段话  BundleTable.EnableOptimizations = true;

将config里面debug=false改一下,运行浏览器试试效果

 

看到只有一个请求,这是否就是我们所要的的呢?

F12打开谷歌开发工具,response看到 a.css b.css里面文件合并在一起

6、这样子做好处:减少http请求,缩短响应时间,提高网页速度,起到优化网站的作用。当然好处不止这些……

原文地址:https://www.cnblogs.com/walleyekneel/p/4118855.html