博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

压缩HTML代码

Posted on 2011-03-21 16:17  linFen  阅读(3754)  评论(0编辑  收藏  举报

/// <summary>
    /// 压缩html代码
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter html = new System.IO.StringWriter();
        HtmlTextWriter tw = new HtmlTextWriter(html);
        base.Render(tw);
        string outhtml = html.ToString();
        outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "\\n+\\s+", string.Empty);
        outhtml = outhtml.Trim();
        writer.Write(outhtml);
    }

禁用不必要的viewstate:这个大家都知道,页面中看不懂的长串字符就是viewstate,这大概会占用15%~40%左右的html代码量,减少viewstate势在必行,如果当前页面没有使用任何viewstate,而且又不想一个控件一个控件的关闭它,可以使用以下代码


 protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter html = new System.IO.StringWriter();
        HtmlTextWriter tw = new HtmlTextWriter(html);
        base.Render(tw);
        string outhtml = html.ToString();
        outhtml = System.Text.RegularExpressions.Regex.Replace(outhtml, "<input\\stype=\"hidden\"\\sname=\"__VIEWSTATE\"\\sid=\"__VIEWSTATE\" value=\".+\\/>", string.Empty);
        outhtml = outhtml.Trim();
        writer.Write(outhtml);
    }