码迷,mamicode.com
首页 > Web开发 > 详细

利用HtmlHelper压缩CSS,JS

时间:2014-10-06 23:10:11      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   文件   sp   div   

 1 //自己拓展HtmlHelper
      public static IHtmlString Script(this HtmlHelper helper, params string[] urls) 2 { 3 var bundleDirectory = "~/bundles/scripts/" + MakeBundleName(".js", urls); 4 var thisBundle = new ScriptBundle(bundleDirectory).Include(urls); 5 BundleTable.Bundles.Add(thisBundle); return Scripts.Render(bundleDirectory); 6 } 7 public static IHtmlString Style(this HtmlHelper helper, params string[] urls) 8 { 9 var bundleDirectory = "~/bundles/styles/" + MakeBundleName(".css", urls); 10 var thisBundle = new StyleBundle(bundleDirectory).Include(urls); 11 BundleTable.Bundles.Add(thisBundle); 12 return Styles.Render(bundleDirectory); 13 } 14 private static string MakeBundleName(string type, params string[] urls) 15 { 16 var bundleSections = new List(); 17 foreach (var item in urls) 18 { 19 bundleSections.Add(item.Replace("~/", "").Replace("/", "_").Replace(type, "")); 20 } 21 return string.Join(";", bundleSections.ToArray()); 22 }

对HtmlHelper进行扩展过后,在前台页面进行,将文件并排包入包中,然后扩展的Helper会把这些CSS进行压缩

1 @section head{ 
2     @Html.Style("~/Content/alice/box/box.css", 
3                 "~/Content/Alice/box/theme/orange.css", 
4                 "~/Content/Alice/tab/tab.css", 
5                 "~/Content/Benefits/CentralPurchasing.css", 
6                 "~/Content/Benefits/Index.css") 
7     }

经过压缩过后,浏览器仍然可以识别css和js的代码,并且减小了文件的大小,浏览速度大大的提高!

效果在项目发布后可以体现出来,所以记得配置IIS。

利用HtmlHelper压缩CSS,JS

标签:style   blog   color   io   ar   for   文件   sp   div   

原文地址:http://www.cnblogs.com/weilai1917/p/4008739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!