Sunday, July 26, 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.

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

private static readonly Regex REGEX_FOR_BREAKS = new Regex(@">[\s]*<",
RegexOptions.Compiled);
protected override void Render(HtmlTextWriter writer)
{
using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter()))
{
base.Render(writer);
string htmlkb = writer.InnerWriter.ToString();
htmlkb = REGEX_FOR_TAGS.Replace(htmlkb, "> <");
htmlkb= REGEX_FOR_BREAKS .Replace(htmlkb, "><");
writer.Write(html.Trim());
}
}

Here in the above code there are two regular expression one for white space in tag and another for whitespace between tag and by just overriding the render event of event you can replace the whitespace.

Happy Coding...

Technorati Tags: ,,,

Share:

4 comments:

  1. This is really nice tip to reduce page size and improve performance.

    Keep up the good work :)

    ReplyDelete
  2. It's nice that you provide code, but have you tried to run that? There is a conflict on variable 'writer'. Just eliminate the 'using' wrapper. Also change the 'htmlkb' variables to 'html'.

    ReplyDelete
  3. That code might easily break something, like whitespaced user input, formatting pres, xml islands, scripts relying on existance of whitespaced text nodes or string constants, etc. - regexing entire stream is just irresponsible
    Also, lines like
    \s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\sLalala
    \s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\sLololo
    not affected.
    Also, why >[\s]*< and not >\s+<?
    Also, I am not sure about calling Render and Response.Write manually, what if some asp.net stuff (control-wise cache, substitutions) will stop working?

    ReplyDelete
  4. No till now it has not break anything.We have use output caching and Appfabric cache with this and It is working fine. So till now overall experience is good.

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews