May 12, 2008

ASP.NET HTML Optimization..

Addition to the ViewState Optimization that we already discussed, our further target could be the extra spaces within the HTML that is being rendered for an aspx page.

No, do not even think of removing all the spaces as that will make the page content unreadablelikethislastwordandthatwedonotwant. But the spaces between the two successive HTML tags (when one ends and another starts) like </div> <div> can be safely removed and also the \n and \r characters are not useful for the browser.

We can take care of this spaces while designing the .aspx page itself but if we remove the spaces at design time then further modification to the page will be a nightmare.

Rather, trap the HTML before it is being sent to the browser and remove those unwanted stuff, and as you might have caught it is the Render method that can be overridden.

The following code can be used to achieve the above desire...

protected override void Render(HtmlTextWriter writer) {
StringWriter stringWriter = new StringWriter();
HtmlTextWriter interceptedHtmlWriter = new HtmlTextWriter(stringWriter, " ");
base.Render(interceptedHtmlWriter);
string interceptedHtml = stringWriter.ToString();
//// Remove the newline and tab characters to decrease the filesize interceptedHtml = interceptedHtml.Replace("\n", "").Replace("\t", "").Replace("\r", "");
//// removing spaces will result in deformatted text on the page so //// only remove the spaces between the HTML tags like <a> </a> which is fine.
interceptedHtml = Regex.Replace(interceptedHtml, ">\\s+<", "><");
writer.Write(interceptedHtml);
}
Put the above method in a class (say BasePage) that inherit the System.Web.UI.Page and then inherit your all other pages from this BasePage
.

IMPORTANT : Make sure your page do not contain embedded javascript with single
line comment. As after removing new line character the following lines to the
line having single line commnent will all be considered as commented lines.


Enjoy........

Submit this story to DotNetKicks

0 comments: