Download mã nguồn ví dụ Tại Đây
1. Nén nội dung HTML là gì
- Các bạn truy cập website sau : LapTrinhViet
- Xem mã nguồn website ( nhấn phím F12) ta thấy mã html được nén lại ( các khoảng trắng , commenr được xóa bỏ ) như hình sau :
- Trong các phiên bản IIS6 , IIS 8 , IIS 8 ... có các tính năng Compress nén html rồi mới trả lại cho Browser .Và các trình duyệt hiện đại cũng hỗ trợ nội dung nén
- Một vấn đề được đặt ra để dùng các tính năng Compress thì cần bật tính năng này trong IIS ( mà không phải nhà cung cấp hosting nào cũng bật tính năng này )
- Ngoài ra với các trình duyệt không hỗ trợ nội dung nén thì vẫn sẽ hiển thị nội dung chưa được nén
- Đồng thời chúng ta không quản lý được mã cũng như nội dung được nén
- Vì thế chúng ta tìm tới giải pháp là viết 1 đoạn code nhỏ dùng để xóa các commnet , khoảng trẳng ngay trong mã nguồn của chúng ta hơn là sử dụng tính năng nén của IIS
- Dưới đây chúng tôi hướng dẫn cách xóa khoảng trắng , commnet trong Webform và MVC
2. Nén nội dung trong ứng dụng MVC
2.1 Nén toàn bộ website
- Đây thực chất là thêm 1 tính năng xóa comment , khoảng trắng cho RazorViewEngine
- Tạo class nén file html như sau :
Mã:
using System.IO;using System.Text;using System.Text.RegularExpressions;using System.Web.Mvc;namespace VinaWebBase.Optimization{ // System.Web.WebPages.dll public abstract class MinifyZipHtml<TModel> : System.Web.Mvc.WebViewPage<TModel> { static Regex REGEX_TAGS = new Regex(@">\s+<", RegexOptions.Compiled); static Regex REGEX_ALL = new Regex(@"\s+|\t\s+|
\s+|
\s+", RegexOptions.Compiled); public override void Write(object value) { if (value != null) { var html = value.ToString(); html = REGEX_TAGS.Replace(html, "> <"); html = REGEX_ALL.Replace(html, " "); if (typeof(MvcHtmlString) == value.GetType()) { value = new MvcHtmlString(html); } else value = html; } base.Write(value); } public override void WriteLiteral(object value) { if (value != null) { var html = value.ToString(); html = REGEX_TAGS.Replace(html, "> <"); html = REGEX_ALL.Replace(html, " "); if (typeof(MvcHtmlString) == value.GetType()) { value = new MvcHtmlString(html); } else value = html; } base.WriteLiteral(value); } }}
Khai báo sử dụng lớp trên để nén các View được trả về trong các resquest
- Tại file cấu hình web.config của View ( View/web.config)
Ta đổi đoạn mã sau :
Mã:
<system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <!--<pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization"/> <add namespace="System.Web.Routing" /> <amespaces> </pages>--> <pages pageBaseType="VinaWebBase.Optimization.MinifyZipHtml"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Optimization"/> <add namespace="System.Web.Routing" /> <amespaces> </pages> </system.web.webPages.razor>
- Chú ý cần khai báo chính xác cả namespace lớp MinifyZipHtml
- Khi sử dụng tính năng bundled của MVC 4 thì cần tham chiếu tới file css , script ảo như file vật lý thông thường , không dùng được các khái báo : @Styles.Render , @Scripts.Render
- Ta có thể khai báo trực tiếp các file CSS , Script ảo như nhứng file css , script thật như sau :
<link href="~/Content/css" rel="stylesheet" />
<script src="~/bundles/modernizr"></script>
<script src="~/bundles/jquery"></script>
- Khi chạy ứng dụng các mã html được zip lại như hình sau :
Download mã nguồn cho MVC chạy Project được kết quả như hình sau :
Kiểm tra mã nguồn ta được kết quả như hình sau :
2.2 Tạo Attribute nén nội dung cho Action của Controller bất kỳ
- Với việc tạo thêm tính năng cho Razor View ở trên thì toàn bộ website sẽ bị nén
- Ta có thể khai báo tính năng nén cho 1 Action cần thiết nào đó như sau :
Tạo lớp Attribute :
Mã:
using System.IO;using System.Text;using System.Text.RegularExpressions;using System.Web.Mvc;namespace VinaWebBase.Optimization{ //using System.Web.Mvc; public class MinifyHtmlFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var response = filterContext.HttpContext.Response; response.Filter = new MinifiedStream(response.Filter); } } public class MinifiedStream : MemoryStream { private readonly Stream _output; public MinifiedStream(Stream stream) { _output = stream; } private static readonly Regex Whitespace = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[
])\s{2,}", RegexOptions.Compiled); public override void Write(byte[] buffer, int offset, int count) { var html = Encoding.UTF8.GetString(buffer); html = Whitespace.Replace(html, string.Empty); html = html.Trim(); _output.Write(Encoding.UTF8.GetBytes(html), offset, Encoding.UTF8.GetByteCount(html)); } }}
Khai báo sử dụng Attribute trong Controller :
Mã:
[VinaWebBase.Optimization.MinifyZipHtmlFilter] public class HomeController : Controller { public ActionResult Index() { return View(); } }
- Có thể khai báo sử dụng cho từng Action như sau :
Mã:
public class HomeController : Controller { [VinaWebBase.Optimization.MinifyZipHtmlFilter] public ActionResult Index() { return View(); } }
3. Nén nội dung trong WebForm
- Đơn giản hơn trong MVC , trong webform các bạn chỉ cần khai báo phương thức sau trong code behind
// Khai báo phương thức sau trong code behind
Mã:
protected override void Render(HtmlTextWriter writer) { if (this.Request.Headers["X-MicrosoftAjax"] != "Delta=true") { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"<script[^>]*>[\w|\t|
|\W]*?</script>"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter sw = new System.IO.StringWriter(sb); HtmlTextWriter hw = new HtmlTextWriter(sw); base.Render(hw); string html = sb.ToString(); System.Text.RegularExpressions.MatchCollection mymatch = reg.Matches(html); html = reg.Replace(html, string.Empty); reg = new System.Text.RegularExpressions.Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[
])\s{2,}|(?=[
])\s{2,}"); html = reg.Replace(html, string.Empty); reg = new System.Text.RegularExpressions.Regex(@"</body>"); string str = string.Empty; foreach (System.Text.RegularExpressions.Match match in mymatch) { str += match.ToString(); } html = reg.Replace(html, str + "</body>"); writer.Write(html); } else base.Render(writer); }
Chạy ứng dụng webform ta được kết quả tương tự như ví dụ về MVC
View more random threads:
Thông qua phân tích dữ liệu Google từ 86 quốc gia, mới đây, một công ty tại Anh đã công bố bảng xếp hạng kích tấc "cậu nhỏ" của các nước trên thế giới. Kết quả, hầu hết các nước xếp ở nhóm đầu của...
"Chim" của chàng trai Việt thuộc...