[Asp.net MVC]Bundle合并,压缩js、css文件

摘要

在web优化中有一种手段,压缩js,css文件,减少文件大小,合并js,css文件减少请求次数。asp.net mvc中为我们提供一种使用c#代码压缩合并js和css这类静态文件的方法。

一个例子

新建asp.net mvc项目,在App_Start文件夹中你可以看到一个叫做BundleConfig.cs的类,

该类内容如下:

 public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
        }
    }

如上代码所示,压缩和合并分两种对象ScriptBundle和StyleBundle。

namespace System.Web.Optimization
{
    //
    // Summary:
    //     Represents a bundle that does Js Minification.
    public class ScriptBundle : Bundle
    {
        //
        // Summary:
        //     Initializes a new instance of the System.Web.Optimization.ScriptBundle class
        //     that takes a virtual path for the bundle.
        //
        // Parameters:
        //   virtualPath:
        //     The virtual path for the bundle.
        public ScriptBundle(string virtualPath);
        //
        // Summary:
        //     Initializes a new instance of the System.Web.Optimization.ScriptBundle class
        //     that takes virtual path and cdnPath for the bundle.
        //
        // Parameters:
        //   virtualPath:
        //     The virtual path for the bundle.
        //
        //   cdnPath:
        //     The path of a Content Delivery Network (CDN).
        public ScriptBundle(string virtualPath, string cdnPath);
    }
}

ScriptBundle有两个构造函数,virtualPath:js文件的虚拟路径,cdnPath:js的网络cdn路径。StyleBundle的构造函数的参数与ScriptBundle相同。

在上面的代码片段中你可以看到

jquery-{version}.js:其中version是jquery的版本号,version是一个版本号的占位符。
jquery.validate*:*通配符,匹配所有。

上面的代码完成后,需要在Global.asax的Application_start事件中对其注册。

如何使用?

在视图中,通过下面的代码实现对静态文件的引用。

浏览

怎么没起作用呢?Bundle默认在调试的情况下,是没有开启打包压缩的,可以通过下面的2中方式进行开启。

再浏览下

你会发现Jquery-1.10.2.js该文件在请求中已经不存在了,它已经被打包压缩在jquery?v=版本号,这个文件里面了。

另外一种打开打包压缩的方式,在web.config文件中中:

总结

上面就是对Bundle的用法介绍,对静态文件打包压缩可以减少请求次数,资源加载的速度。

posted @ 2017-02-25 10:58  wolfy  阅读(2547)  评论(1编辑  收藏  举报