摘要
在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的用法介紹,對靜態文件打包壓縮可以減少請求次數,資源加載的速度。