Thursday, August 13, 2009

How to remove white spaces between tags and lines of html render by asp.net page ?

When asp.net page loaded in to browser there are lots of white spaces between tags and in tags that will increase your html kb. For example if your page around 300 kb then it will take 3 second to load on 100 kbps internet connection and in dial up connection it will still take time. So if you want to load your site fast on dial up internet connection then you need to decrease html kb as much you can and removing white spaces from the html will be good idea for that.
Following is the code for the page on which you want to remove white spaces from the html. It will decrease your html kb by 30 percentage.

using System.Text;
using System.Text.RegularExpressions;

private static readonly Regex REGEX_BETWEEN_TAGS = new Regex(@">\s+<", RegexOptions.Compiled);

private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s+", RegexOptions.Compiled);


///
/// Initializes the object and calls on the child
/// controls of the to render.
///

/// The that receives the page content.
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
{
this.Page.Title = CommonFunctions.HtmlEncode(this.Page.Title);
base.Render(htmlwriter);
string html = htmlwriter.InnerWriter.ToString();

html = REGEX_BETWEEN_TAGS.Replace(html, "> <");
html = REGEX_LINE_BREAKS.Replace(html, string.Empty);

writer.Write(html.Trim());
}

}

1 comment:

  1. One of the efforts for increasing the performance of the asp.net websites.

    ReplyDelete