文章内容

2017/8/5 14:09:57,作 者: 黄兵

Asp.net mvc 性能优化,合并和压缩(bundle and minification)

Asp.net mvc 4和之后的版本支持Asp.net4.5包含的bundling and minification框架。Bunlding指的是把多个css或者javascript文件合并成一个文件,这样可以减少收到的http请求的个数,从而缩短页面的第一次加载时间。Minification指的是压缩javascript文件或者css文件,使用的技术包括去掉空格和注释,把变量名字变短,

应用bundle和minification功能包括三个步骤:

  • 创建Bundle
  • 在View里引用创建的bundle
  • 激活bundle和minification功能

创建Bundle

您可以在文件App_Start\BundleConfig.cs的方法RegisterBundles里添加新的bundle,比如下面的代码创建一个script bundle

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));
下面的代码创建一个style bundle
 bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));

上面的例子使用Include方法把css或者js文件包含到Bundle里,参数是一个字符串数组, 每个字符串是一个虚拟路径。你还可以使用方法IncludeDirectory添加一个目录(可以包含全部的子目录)下面满足search pattern的所有文件。

引用Bundle

在view里使用Render方法来引用Bundles,对于Css文件是Styles.Render ,对于Javascript是Scripts.Render。

 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class=" fix-container">
        @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

激活Bundle和Minification

你可以通过设置web.config里的compilation元素的debug属性打开或者关闭bundle和minifaction功能,debug="true"的时候,bundle和minification功能关闭,false的时候打开, 默认值是false。

<system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
</system.web>

你还可以通过设置类BundleTable的属性EnableOptimizations为true覆盖掉web.config里的设置,打开bundle和minification功能。

public static void RegisterBundles(BundleCollection bundles)
{
    //create new bundle and add to bundles.

    BundleTable.EnableOptimizations = true;
}

几点思考

如果更新了bundle里的一个文件,bundle url里的query string部分会变化,这样新的请求就会重新下载这个bundle(不使用缓存里的)。因此经常会变化的资源不适合放到bundle里。

对于页面的加载时间来说, bundle和minification主要的作用是提供第一次访问的加载时间,这主要是因为浏览器会缓存收到的bundle。

Bundle类所在的命名空间System.Web.Optimization是由System.Web.Optimization.DLL实现。它利用WebGrease.dll进行minification。WebGrease.dll依赖Antlr3.Runtime.dll。

本文转载自:HelpSd - Asp.net mvc 性能优化,合并和压缩(bundle and minification)

分享到:

发表评论

评论列表