Mar
21
2013
SEO

How To Remove The HTML White Space in ASP.NET C#

Remove the HTML white space at runtime will reduce the HTML page size so the web page will be loading faster. This method is for SEO purposes.

Add the code below to any ASPX.CS page or Master page, then browse the page to see the magic.

 

using System.Text.RegularExpressions;


//BEGIN: Removing HTML white Space. #####################################################################
        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);

        protected override void Render(HtmlTextWriter writer)
        {
            using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
            {
                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());
            }
        }

//END: Removing HTML white Space. #####################################################################

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Calendar

<<  February 2021  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567

View posts in large calendar