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: HTMLKb,ASP.NET,Whitespace,Performance
This is really nice tip to reduce page size and improve performance.
ReplyDeleteKeep up the good work :)
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'.
ReplyDeleteThat 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
ReplyDeleteAlso, 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?
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