Friday, December 31, 2010

Minify HTML Output of an ASPX Page Before Sending it to Client

We can Minify HTML Output of an ASPX Page Before Sending it to Client by Overriding the page Render event.

protected override void Render(HtmlTextWriter writer)
{
TextWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
String html = output.ToString();
html = Regex.Replace(html, @"\n|\t", " ");
html = Regex.Replace(html, @">\s+<", "><").Trim();
html = Regex.Replace(html, @"\s{2,}", " ");
writer.Write(html);
}


But the problem with the above code is that we need to add it to Code-Behind of all .aspx page.
This event can not be overriden in Master Page and that is not a strong OOP concept too.

The better solution is to Create our own Page Class(eg: MyPageClass) by Inheriting from System.Web.UI.Page and Put the above code in it. Now inherit all Code-Behind files(.aspx.cs) from our own Page Class(eg: MyPageClass). Complete Code is given below.

//Custom Page Class - Put this in App_Code Folder 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;

///
/// Summary description for MyPageBase
///

public class MyPageBase : System.Web.UI.Page
{


public MyPageBase()
{
//Constructor code here
}

//Override the page Render event for HTML Output Minification. This event can not be overriden in Master Page and that is not a strong OOP concept too.
protected override void Render(HtmlTextWriter writer)
{
TextWriter output = new StringWriter();
base.Render(new HtmlTextWriter(output));
String html = output.ToString();
html = Regex.Replace(html, @"\n|\t", " ");
html = Regex.Replace(html, @">\s+<", "><").Trim();
html = Regex.Replace(html, @"\s{2,}", " ");
writer.Write(html);
}
}

Inherit the .aspx.cs File from MyPageBase class

using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Xml;
using System.Xml.Linq;

public partial class Default : MyPageBase
{

protected void Page_Load(object sender, EventArgs e)
{
 
}

}

In my next post i will teach how to do this using Plug-n-Play HttpModule

No comments:

Post a Comment