Bundling and Minification(轉)

原文地址:https://go.microsoft.com/fwlink/?LinkId=301862javascript

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)css

在Asp.Net4.5中,爲了改善請求加載時間,你可能使用到兩個技術:捆綁和壓縮。綁定和壓縮經過減小對服務的請求次數和減小請求資源(如css和js)的大小的方式來改善請求加載時間。html

Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser. In the image below, the IE F12 developer tools network tabs shows the timing for assets required by the About view of a sample application.java

當前大多數主流瀏覽器會把對同一主機的併發鏈接數限制在6個。這意味着針對一個主機的正在處理的鏈接數達到六個之後,瀏覽器會將新增的資源請求排隊。以下圖,在IE瀏覽器的F12開發者工具中的Network標籤頁中能夠看到對示例應用程序的About頁面進行訪問時,各個資源請求的耗時狀況。jquery

B/M

The gray bars show the time the request is queued by the browser waiting on the six connection limit. The yellow bar is the request time to first byte, that is, the time taken to send the request and receive the first response from the server. The blue bars show the time taken to receive the response data from the server. You can double-click on an asset to get detailed timing information. For example, the following image shows the timing details for loading the /Scripts/MyScripts/JavaScript6.js file.web

灰色條顯示了由於六個連接限制,而被瀏覽器排隊的請求的等待時間。黃色條表示第一個字符的時間,即發送請求並從服務器接收到第一個響應所花費的時間。藍色條表示從服務器接收響應數據所花費的時間。你能夠雙擊一個資源查看詳細的時間花費信息。好比,下圖顯示了加載/Scripts/MyScripts/JavaScript6.js 文件所花費的時間明細。ajax

The preceding image shows the Start event, which gives the time the request was queued because of the browser limit the number of simultaneous connections. In this case, the request was queued for 46 milliseconds waiting for another request to complete.數組

經過上圖能夠看出,由於瀏覽器對併發鏈接的數目限制,該請求花費在排隊上的時間。在這個例子中,該請求在隊列中等待了46毫秒直到另外一個請求完成。瀏覽器

Bundling 捆綁

Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.緩存

綁定是Asp.Net4.5的一個新功能,該功能能夠很容易的把多個文件聯合或者捆綁成一個單獨的文件。你能夠建立Css,js或者其餘軟件集。文件越少,Http請求就越少,從而優化首頁的加載性能。

The following image shows the same timing view of the About view shown previously, but this time with bundling and minification enabled.

啓用捆綁和壓縮功能之後,再次訪問示例應用程序的About頁面,下圖顯示此處的時序視圖。

Minification 壓縮

Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character. Consider the following JavaScript function.

壓縮功能對scripts和css執行各類不一樣的代碼優化,例如去除沒必要要的空格、註釋,縮減變量名爲一個字符。考慮下面的js函數。

AddAltToImg = function (imageTagAndImageID, imageContext) {
    ///<signature>
    ///<summary> Adds an alt tab to the image
    // </summary>
    //<param name="imgElement" type="String">The image selector.</param>
    //<param name="ContextForImage" type="String">The image context.</param>
    ///</signature>
    var imageElement = $(imageTagAndImageID, imageContext);
    imageElement.attr('alt', imageElement.attr('id').replace(/ID/, ''));
}

After minification, the function is reduced to the following:壓縮之後,該函數被縮減成下面這樣

AddAltToImg = function (n, t) { var i = $(n, t); i.attr("alt", i.attr("id").replace(/ID/, "")) }

In addition to removing the comments and unnecessary whitespace, the following parameters and variable names were renamed (shortened) as follows:

除了去除註釋和沒必要要的空格,下列參數和變量名也被重命名:

Original Renamed
imageTagAndImageID n
imageContext t
imageElement i

Impact of Bundling and Minification 捆綁和壓縮的影響

The following table shows several important differences between listing all the assets individually and using bundling and minification (B/M) in the sample program.

下表顯示了示例程序在使用壓縮技術先後的幾點重要的不一樣之處:

  Using B/M Without B/M Change
File Requests 9 34 256%
KB Sent 3.26 11.92 266%
KB Received 388.51 530 36%
Load Time 510 MS 780 MS 53%

The bytes sent had a significant reduction with bundling as browsers are fairly verbose with the HTTP headers they apply on requests. The received bytes reduction is not as large because the largest files (Scripts\jquery-ui-1.8.11.min.js and Scripts\jquery-1.7.1.min.js) are already minified. Note: The timings on the sample program used the Fiddler tool to simulate a slow network. (From the Fiddler Rules menu, select Performance then Simulate Modem Speeds.)

瀏覽器在發送字段的時候經過捆綁有一個很大的縮減,由於包含在請求中的http頭文件是很冗長的。可是接收字段的縮減就不是很明顯了,由於最大的文件(Scripts\jquery-ui-1.8.11.min.js and Scripts\jquery-1.7.1.min.js)已是最小的了。注意:示例程序的時間是經過Fiddler工具模擬一個較慢的網絡得到的(在fiddler規則菜單中,選擇 performance 而後選擇 Simulate Modem Speeds)。

Debugging Bundled and Minified JavaScript 調試綁定和壓縮javascript

It's easy to debug your JavaScript in a development environment (where the compilation Element in the Web.config file is set to debug="true" ) because the JavaScript files are not bundled or minified. You can also debug a release build where your JavaScript files are bundled and minified. Using the IE F12 developer tools, you debug a JavaScript function included in a minified bundle using the following approach:

在開發環境中調試javascript很容易(在web.config中的編譯要素下設置debug="true"),由於javascript文件是未捆綁未壓縮的。你也能夠調試發佈版本,儘管其中的javascript是捆綁壓縮過的。使用IE的F12開發者工具,能夠下列方式調試一個包含在壓縮過的js函數:

  1. Select the Script tab and then select the Start debugging button.選擇Script標籤頁,點擊Start debugging按鈕。
  2. Select the bundle containing the JavaScript function you want to debug using the assets button.經過資源按鈕選擇你想調試的javascript函數
  3. Format the minified JavaScript by selecting the Configuration button , and then selecting Format JavaScript.點擊Configuration button按鈕格式化壓縮的javascript,而後選擇格式化之後的js。
  4. In the Search Scrip t input box, select the name of the function you want to debug. In the following image, AddAltToImg was entered in the Search Scrip t input box.在搜索框中,輸入你要調試的js函數的名字。在下圖中,在搜索框中輸入AddAltToImg

For more information on debugging with the F12 developer tools, see the MSDN article Using the F12 Developer Tools to Debug JavaScript Errors.

更多關於調試的信息,查看Using the F12 Developer Tools to Debug JavaScript Errors.

Controlling Bundling and Minification 控制捆綁和壓縮

Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file. In the following XML, debug is set to true so bundling and minification is disabled.

經過設置web.config編譯元素中的debug屬性啓動或者關閉捆綁壓縮功能。在下面的xml中,debug被設置爲真,從而關閉捆綁壓縮功能。

<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>

To enable bundling and minification, set the debug value to "false". You can override the Web.config setting with the EnableOptimizations property on the BundleTable class. The following code enables bundling and minification and overrides any setting in the Web.config file.

要啓用捆綁壓縮功能,設置debug="false"。能夠經過BundleTable類的EnableOptimizations屬性重寫web.config設置。下列代碼啓用捆綁壓縮,能夠重置web.config中的相關設置。

 

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

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}
Note

Unless EnableOptimizations is true or the debug attribute in the compilation Element in the Web.config file is set to false, files will not be bundled or minified. Additionally, the .min version of files will not be used, the full debug versions will be selected. EnableOptimizations overrides the debug attribute in the compilation Element in the Web.config file

EnableOptimizations爲true而且web.comfig文件中compilation Element的debug屬性設置成false,文件纔會被捆綁壓縮。此外,.min版本的文件不會被採用,將選擇完整的調試版本。(什麼意思?)。EnableOptimizations覆蓋web.config中的dubug屬性。(這段理解好像有問題。)

 Using Bundling and Minification with ASP.NET Web Forms and Web Pages 在Asp.Net webForms 和WebPages中使用捆綁壓縮

Using Bundling and Minification with ASP.NET MVC 在Asp.Net MVC中使用捆綁壓縮

In this section we will create an ASP.NET MVC project to examine bundling and minification. First, create a new ASP.NET MVC internet project named MvcBM without changing any of the defaults.

在這一節咱們將建立一個Asp.net MVC項目檢查捆綁壓縮功能。首先,建立一個asp.net mvc項目,命名爲MvcBM,先不要作任何修改。

Open the App_Start\BundleConfig.cs file and examine the RegisterBundles method which is used to create, register and configure bundles. The following code shows a portion of the RegisterBundles method.

打開App_Start\BundleConfig.cs文件,檢查RegisterBundles方法,該方法用來建立、註冊並配置捆綁。下面的代碼顯示了RegisterBundles方法的一部分。

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

The preceding code creates a new JavaScript bundle named ~/bundles/jquery that includes all the appropriate (that is debug or minified but not .vsdoc) files in the Scripts folder that match the wild card string "~/Scripts/jquery-{version}.js". For ASP.NET MVC 4, this means with a debug configuration, the file jquery-1.7.1.js will be added to the bundle. In a release configuration, jquery-1.7.1.min.js will be added. The bundling framework follows several common conventions such as:

前面的代碼建立了一個名字爲"~/bundles/jquery"的js包,其中包含Scripts文件夾中全部匹配通配符「~/Scripts/jquery-{version}.js」的文件。對於mvc4來講,這意味着在調試配置下 jquery-1.7.1.js將被添加到包中。在發佈配置中,jquery-1.7.1.min.js將被添加到保證。捆綁框架遵照幾個通用的約定:

    • Selecting ".min" file for release when "FileX.min.js" and "FileX.js" exist. 在發佈版本中,當fileX.min.js和fileX.js共存時,選擇.min文件
    • Selecting the non ".min" version for debug. 在調試版本中,選擇沒有.min 的文件。
    • Ignoring "-vsdoc" files (such as jquery-1.7.1-vsdoc.js), which are used only by IntelliSense.忽略 -vsdoc 文件,該類文件只有在智能感知的時候有用。

The {version} wild card matching shown above is used to automatically create a jQuery bundle with the appropriate version of jQuery in your Scripts folder. In this example, using a wild card provides the following benefits:

上面顯示的「{version}」通配符用來自動建立一個包含scripts文件夾下匹配版本的jquery包。在這個例子中,使用通配符提供瞭如下有點:

    • Allows you to use NuGet to update to a newer jQuery version without changing the preceding bundling code or jQuery references in your view pages.在不修改以前捆綁代碼和view視圖中jquery引用的狀況下,經過Nuget升級到一個新的jquery版本
    • Automatically selects the full version for debug configurations and the ".min" version for release builds.自動爲調試配置選擇完整版本,爲發佈配置選擇".min"版本。

Using a CDN 

The follow code replaces the local jQuery bundle with a CDN jQuery bundle. 下列代碼使用內容分發網絡jquery包替代本地jquery包

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

    bundles.UseCdn = true;   //enable CDN support

    //add link to jquery on the CDN
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";

    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));

    // Code removed for clarity.
}

In the code above, jQuery will be requested from the CDN while in release mode and the debug version of jQuery will be fetched locally in debug mode. When using a CDN, you should have a fallback mechanism in case the CDN request fails. The following markup fragment from the end of the layout file shows script added to request jQuery should the CDN fail.

在上面的代碼中,發佈模式下,jquery從CDN獲取;調試模式下,從本地獲取調試版本的jquery。當使用CDN時,須要有一個後備機制,以防CDN請求失敗。如下標記片斷位於佈局文件的結尾處,其顯示了當CDN請求失敗後,向要求的jquery中添加腳本。

</footer>

        @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> 

        @RenderSection("scripts", required: false)
    </body>
</html>

Creating a Bundle

The Bundle class Include method takes an array of strings, where each string is a virtual path to resource. The following code from the RegisterBundles method in the App_Start\BundleConfig.cs file shows how multiple files are added to a bundle:

Bundle類的Include方法接受一個字符串數組,每一個字符串都是一個資源虛擬路徑。App_Start\BundleConfig.cs中的ResisterBundles方法顯示瞭如何把多個文件添加到捆綁包中:

bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
    "~/Content/themes/base/jquery.ui.core.css",
    "~/Content/themes/base/jquery.ui.resizable.css",
    "~/Content/themes/base/jquery.ui.selectable.css",
    "~/Content/themes/base/jquery.ui.accordion.css",
    "~/Content/themes/base/jquery.ui.autocomplete.css",
    "~/Content/themes/base/jquery.ui.button.css",
    "~/Content/themes/base/jquery.ui.dialog.css",
    "~/Content/themes/base/jquery.ui.slider.css",
    "~/Content/themes/base/jquery.ui.tabs.css",
    "~/Content/themes/base/jquery.ui.datepicker.css",
    "~/Content/themes/base/jquery.ui.progressbar.css",
    "~/Content/themes/base/jquery.ui.theme.css"));

The Bundle class IncludeDirectory method is provided to add all the files in a directory (and optionally all subdirectories) which match a search pattern. The Bundle class IncludeDirectory API is shown below:

Bundle類的IncludeDirectory方法可以把與查詢模版匹配的目錄(任意子目錄)的全部文件都添加到捆綁包中。IncludeDirectoryde API以下:

public Bundle IncludeDirectory(
    string directoryVirtualPath,  // The Virtual Path for the directory.
    string searchPattern)         // The search pattern.

public Bundle IncludeDirectory(
    string directoryVirtualPath,  // The Virtual Path for the directory.
    string searchPattern,         // The search pattern.
    bool searchSubdirectories)    // true to search subdirectories.

Bundles are referenced in views using the Render method, ( Styles.Render for CSS and Scripts.Render for JavaScript). The following markup from the Views\Shared\_Layout.cshtml file shows how the default ASP.NET internet project views reference CSS and JavaScript bundles.

在視圖中經過Render方法引用Bundles,(css使用Style.Render,js使用Scripts.Render).下面是一段來自於Views\Shared\_Layout.cshtml的代碼,從中咱們能夠看到在Asp.net網站項目中的默認視圖中是如引用css和js捆綁包的。

<!DOCTYPE html>
<html lang="en">
<head>
    @* Markup removed for clarity.*@    
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @* Markup removed for clarity.*@
   
   @Scripts.Render("~/bundles/jquery")
   @RenderSection("scripts", required: false)
</body>
</html>

Notice the Render methods takes an array of strings, so you can add multiple bundles in one line of code. You will generally want to use the Render methods which create the necessary HTML to reference the asset. You can use the Url method to generate the URL to the asset without the markup needed to reference the asset. Suppose you wanted to use the new HTML5 async attribute. The following code shows how to reference modernizr using the Url method.

注意Render方法接受一組字符串,這意味着你能夠在一行代碼中添加多個捆綁包。你一般會使用建立必要Heml的Render方法去引用資源。你可使用Url方法生成資源的URL,而不須要引用資源的標記。若是你想要使用Html5中的async屬性。下面的代碼顯示瞭如何使用Url方法去引用modernizr

<head>
    @*Markup removed for clarity*@
    <meta charset="utf-8" />
    <title>@ViewBag.Title - MVC 4 B/M</title>
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    @Styles.Render("~/Content/css")

   @* @Scripts.Render("~/bundles/modernizr")*@

    <script src='@Scripts.Url("~/bundles/modernizr")' async> </script>
</head>

 

Using the "*" Wildcard Character to Select Files 使用‘*’通配符選擇文件

The virtual path specified in the Include method and the search pattern in the IncludeDirectory method can accept one "*" wildcard character as a prefix or suffix to in the last path segment. The search string is case insensitive. The IncludeDirectory method has the option of searching subdirectories.

Include方法中的虛擬路徑和IncludeDirectory方法中的搜索模版可使用‘*’通配符做爲最後一個路徑段的前綴或者後綴。查詢字段對大小寫不敏感。IncludeDirectory方法能夠設置是否搜索子目錄。

Consider a project with the following JavaScript files:考慮包含一下js文件的項目:

    • Scripts\Common\AddAltToImg.js
    • Scripts\Common\ToggleDiv.js
    • Scripts\Common\ToggleImg.js
    • Scripts\Common\Sub1\ToggleLinks.js

The following table shows the files added to a bundle using the wildcard as shown:下表顯示了使用通配符時被添加到捆綁包中的文件:

Call Files Added or Exception Raised
Include("~/Scripts/Common/*.js") AddAltToImg.js, ToggleDiv.js, ToggleImg.js
Include("~/Scripts/Common/T*.js") Invalid pattern exception. The wildcard character is only allowed on the prefix or suffix.
Include("~/Scripts/Common/*og.*") Invalid pattern exception. Only one wildcard character is allowed.
"Include("~/Scripts/Common/T*") ToggleDiv.js, ToggleImg.js
"Include("~/Scripts/Common/*") Invalid pattern exception. A pure wildcard segment is not valid.
IncludeDirectory("~/Scripts/Common", "T*") ToggleDiv.js, ToggleImg.js
IncludeDirectory("~/Scripts/Common", "T*",true) ToggleDiv.js, ToggleImg.js, ToggleLinks.js

 

Explicitly adding each file to a bundle is generally the preferred over wildcard loading of files for the following reasons:首選通配符加載明確的文件到捆綁包中,緣由以下:

    • Adding scripts by wildcard defaults to loading them in alphabetical order, which is typically not what you want. CSS and JavaScript files frequently need to be added in a specific (non-alphabetic) order. You can mitigate this risk by adding a custom IBundleOrderer implementation, but explicitly adding each file is less error prone. For example, you might add new assets to a folder in the future which might require you to modify your IBundleOrderer implementation.經過通配符加載文檔默認是按照字母順序加載的,這可能不是你想要的。Css和js一般須要以特定的順序添加。你能夠實現一個IBundleOrderer接口下降風險,可是明確添加每一個文件使錯誤的可能性更小。例如:之後若是要添加一個新的資源到目錄中,就不得不修改IbundleOrderer的實現。
    • View specific files added to a directory using wild card loading can be included in all views referencing that bundle. If the view specific script is added to a bundle, you may get a JavaScript error on other views that reference the bundle.把特定視圖文件添加到一個用通配符載入的字典中,該文件將會包含在全部引用了該捆綁包的視圖中。若是特定視圖腳本添加到一個捆綁包中,在另外一個引用了該捆綁包的視圖中可能會出現一個js錯誤。
    • CSS files that import other files result in the imported files loaded twice. For example, the following code creates a bundle with most of the jQuery UI theme CSS files loaded twice.引用過其餘文件的css文件可能致使被引用的文件被載入兩次。例如,下面的代碼建立一個捆綁包,其中大部分jQuery UI主題CSS文件加載了兩次。

bundles.Add(new StyleBundle("~/jQueryUI/themes/baseAll")
    .IncludeDirectory("~/Content/themes/base", "*.css"))

 The wild card selector "*.css" brings in each CSS file in the folder, including the Content\themes\base\jquery.ui.all.css file. The jquery.ui.all.css file imports other CSS files.通配符選擇器「*.css」導入文件夾下的每個css文件,包括Content\themes\base\jquery.ui.all.css文件。該文件導入其餘css文件。

Bundle Caching 捆綁緩存

Bundles set the HTTP Expires Header one year from when the bundle is created. If you navigate to a previously viewed page, Fiddler shows IE does not make a conditional request for the bundle, that is, there are no HTTP GET requests from IE for the bundles and no HTTP 304 responses from the server. You can force IE to make a conditional request for each bundle with the F5 key (resulting in a HTTP 304 response for each bundle). You can force a full refresh by using ^F5 (resulting in a HTTP 200 response for each bundle.)

捆綁包建立時,設置Http過時頭爲一年。若是你導航到以前的視圖頁,Fiddler顯示IE沒有發起對捆綁包的條件請求,也就是說,IE沒有發起get請求,服務器也沒有304響應。你能夠經過F5鍵強制IE爲每個捆綁包發起條件請求(每一個捆綁包獲得一個http304響應)。也可使用ctrl+F5徹底強制刷新(每一個捆綁包獲得一個http200響應)。

The following image shows the Caching tab of the Fiddler response pane:下圖顯示Fiddler響應窗口的Caching標籤頁。

fiddler caching image

The request http://localhost/MvcBM_time/bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81
is for the bundle AllMyScripts and contains a query string pair v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81. The query string v has a value token that is a unique identifier used for caching. As long as the bundle doesn't change, the ASP.NET application will request the AllMyScripts bundle using this token. If any file in the bundle changes, the ASP.NET optimization framework will generate a new token, guaranteeing that browser requests for the bundle will get the latest bundle.

請求 http://localhost/MvcBM_time/bundles/AllMyScripts?v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81獲取捆綁包AllMyScripts而且包含一個查詢字符串對v=r0sLDicvP58AIXN_mc3QdyVvVj5euZNzdsa2N1PKvb81.查詢字符串v有一個token值,它是用於緩存的惟一標識符。只要捆綁包沒有改變,Asp.Net一直使用該token請求AllMyScripts捆綁包。若是捆綁包中的任何文件被改變,Asp.Net優化框架將會生成一個新的token,確保瀏覽器可以獲取最新的捆綁包。

If you run the IE9 F12 developer tools and navigate to a previously loaded page, IE incorrectly shows conditional GET requests made to each bundle and the server returning HTTP 304. You can read why IE9 has problems determining if a conditional request was made in the blog entry Using CDNs and Expires to Improve Web Site Performance.

若是你運行IE9 F12開發者工具並導航到以前載入的頁面,IE會錯誤的顯示對每一個捆綁包的條件get請求以及服務器的304響應。你能夠閱讀博客 Using CDNs and Expires to Improve Web Site Performance 瞭解爲何IE9在決定是否發起一個條件請求時存在問題。

LESS, CoffeeScript, SCSS, Sass Bundling.

The bundling and minification framework provides a mechanism to process intermediate languages such as SCSS, Sass, LESS or Coffeescript, and apply transforms such as minification to the resulting bundle. For example, to add .less files to your MVC 4 project:

綁定和壓縮框架提供了一種機制,該機制用來處理諸如SCSS,Sass,LESS或者Coffeescript這樣的中間語言並將此類壓縮轉換爲結果壓縮包。例如,添加.less文件到你的MVC4項目:

  1. Create a folder for your LESS content. The following example uses the Content\MyLess folder.爲LESS內容建立一個文件。下面這個例子使用文件夾Content\MyLess
  2. Add the .less NuGet package dotless to your project.添加.less Nuget包dotless到你的項目。
    NuGet dotless install
  3. Add a class that implements the IBundleTransform interface. For the .less transform, add the following code to your project.添加一個實現了IBundleTransfrom接口的類。爲了轉換.less,添加下列代碼到你的項目中。

    using System.Web.Optimization;
    
    public class LessTransform : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            response.Content = dotless.Core.Less.Parse(response.Content);
            response.ContentType = "text/css";
        }
    }

     

  4. Create a bundle of LESS files with the LessTransform and the CssMinify transform. Add the following code to the RegisterBundles method in the App_Start\BundleConfig.cs file.使用LessTransform和CssMinify轉換去建立一個LESS文件的捆綁包。添加下面的代碼到App_Start\BundleConfig.cs文件的RegisterBundles方法

    var lessBundle = new Bundle("~/My/Less").IncludeDirectory("~/My", "*.less");
    lessBundle.Transforms.Add(new LessTransform());
    lessBundle.Transforms.Add(new CssMinify());
    bundles.Add(lessBundle);

     

  5. Add the following code to any views which references the LESS bundle.添加下面的代碼到任意調用less捆綁包的視圖。

    @Styles.Render("~/My/Less");

     

Bundle Considerations 捆綁注意事項

A good convention to follow when creating bundles is to include "bundle" as a prefix in the bundle name. This will prevent a possible routing conflict.建立捆綁包是使用「bundle」做爲前綴是一個應該遵循的很好的約定。這樣能夠防止可能的路由衝突。

Once you update one file in a bundle, a new token is generated for the bundle query string parameter and the full bundle must be downloaded the next time a client requests a page containing the bundle. In traditional markup where each asset is listed individually, only the changed file would be downloaded. Assets that change frequently may not be good candidates for bundling.一旦你修改了捆綁包中的一個文件,針對捆綁包的查詢參數將會生成一個新的token,而且下次客戶端請求包含該捆綁包的頁面時,整個捆綁包都須要從新下載。在每一個資源被單獨列出的傳統標記中,只有被修改的文件被下載。常常被修改的資源不適合捆綁。

Bundling and minification primarily improve the first page request load time. Once a webpage has been requested, the browser caches the assets (JavaScript, CSS and images) so bundling and minification won't provide any performance boost when requesting the same page, or pages on the same site requesting the same assets. If you don't set the expires header correctly on your assets, and you don't use bundling and minification, the browsers freshness heuristics will mark the assets stale after a few days and the browser will require a validation request for each asset. In this case, bundling and minification provide a performance increase after the first page request. For details, see the blog Using CDNs and Expires to Improve Web Site Performance.捆綁和壓縮主要改善頁面的首次加載時間。一旦頁面是被請求過的,瀏覽器緩存各類資源(js,css,圖片),因此訪問同一個頁面或者同一個網站的相同資源,綁定和壓縮不會起到任何優化的效果。若是你沒有給資源設置正確的過時頭信息或者沒用使用綁定和壓縮,瀏覽器新鮮度試探法將會在幾天之後標記資源過時,瀏覽器將會爲每一個資源從新發送有效的請求。這種狀況下,綁定和壓縮在頁面第一次請求後提高了性能。關於細節,請查看博客Using CDNs and Expires to Improve Web Site Performance

The browser limitation of six simultaneous connections per each hostname can be mitigated by using a CDN. Because the CDN will have a different hostname than your hosting site, asset requests from the CDN will not count against the six simultaneous connections limit to your hosting environment. A CDN can also provide common package caching and edge caching advantages.使用CDN能夠緩解瀏覽器對於一個主機只能有6個併發的限制,由於CDN的主機名與主站點不一樣,對CDN的資源請求數不會佔用主機的併發。CDN也能夠提供通用包緩存和邊緣緩存的有點。

Bundles should be partitioned by pages that need them. For example, the default ASP.NET MVC template for an internet application creates a jQuery Validation bundle separate from jQuery. Because the default views created have no input and do not post values, they don't include the validation bundle.捆綁包會被須要他們的頁面分割。例如,網站程序的默認Asp.Net MVC模版建立一個從jquery分離的jquery驗證包。由於默認建立的視圖沒有輸入,不傳遞值,因此不包含驗證包。

The System.Web.Optimization namespace is implemented in System.Web.Optimization.DLL. It leverages the WebGrease library (WebGrease.dll) for minification capabilities, which in turn uses Antlr3.Runtime.dll.System.Web.Optimization命名空間在System.Web.Optimization.DLL中實現。它利用了WebFrease庫的壓縮能力,也能夠是用Antlr3.Runtime.dll

I use Twitter to make quick posts and share links. My Twitter handle is: @RickAndMSFT

相關文章
相關標籤/搜索