Sunday, July 26, 2009

How to remove white spaces between tags and lines of html render by page

When 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]*<",
protected override void Render(HtmlTextWriter writer)
using (HtmlTextWriter writer = new HtmlTextWriter(new System.IO.StringWriter()))
string htmlkb = writer.InnerWriter.ToString();
htmlkb = REGEX_FOR_TAGS.Replace(htmlkb, "> <");
htmlkb= REGEX_FOR_BREAKS .Replace(htmlkb, "><");

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: ,,,



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

    Keep up the good work :)

  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'.

  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
    not affected.
    Also, why >[\s]*< and not >\s+<?
    Also, I am not sure about calling Render and Response.Write manually, what if some stuff (control-wise cache, substitutions) will stop working?

  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.


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

Search This Blog
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews