最近研究程序的优化,压缩html可以减小html的体积,有利于提高页面的相应速度。在webform的basepage中添加如下代码:
1 /// <summary> 2 /// 重写Render方法,来压缩输出的内容 3 /// </summary> 4 /// <param name="writer"></param> 5 protected override void Render(HtmlTextWriter writer) 6 { 7 StringWriter html = new StringWriter(); 8 HtmlTextWriter tw = new HtmlTextWriter(html); 9 base.Render(tw); 10 11 string outhtml = html.ToString(); 12 13 outhtml = Regex.Replace(outhtml, @"s+", " ", RegexOptions.Compiled | RegexOptions.Multiline); 14 outhtml = Regex.Replace(outhtml, "\r\n", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline); 15 outhtml = Regex.Replace(outhtml, @"(?<=>)(s| | )+(?=<)", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline); 16 outhtml = Regex.Replace(outhtml, "<!--*.*?-->", string.Empty, RegexOptions.Compiled | RegexOptions.Multiline); 17 18 19 //输出到客户端 20 writer.Write(outhtml); 21 }
具体到相应项目当中,还是需要调试以下,以免过滤需要输出的内容。