標籤:style blog http io ar os 使用 sp 檔案
建立一個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開啟Google開發工具,response看到 a.css b.css裡面檔案合并在一起
6、這樣子做好處:減少http請求,縮短回應時間,提高網頁速度,起到最佳化網站的作用。當然好處不止這些……
mvc4開篇之BundleConfig(1)