Strip space before page rendering

  • Thread starter Thread starter vMike
  • Start date Start date
V

vMike

Is there any benefit to stripping all the space from the page before
rendering by overriding the page render and using the htmltextwriter and
stringbuilder to strip linefeeds, tabs and extra space etc. I have noticed
that may site's source code is like this. Is this because it is better for
the browser or harder for someone to be able to read it. Or maybe there is a
method or command to do this automatically?

Any thoughts are appreciated.

Mike
 
I don't think there is a way to do it automatically, but it's simple enough
to implement.

This is the approach I use:

I have a base class derived from System.Web.UI.Page and override Render

namespace DoNot.Invade.MySpace
{
class Page : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);

base.Render (hw);

string html = sb.ToString();

html = html.Replace(Environment.NewLine, string.Empty);
html = html.Replace("\n", string.Empty); // This may be redundant
html = html.Replace("\t", string.Empty);

writer.Write(html);
}
}
}

Hope this helps
Brian W
 
Thanks, I had something similar to that. The only thing I had to do was do
remove the <!-- that asp puts before the javascipt for postback because when
I removed the rest of the line is caused an error. But I wonder is stripping
the space make the page display any quicker in the browser as I image there
is a small amount of overhead on the server side.
 
Brian said:
I don't think there is a way to do it automatically, but it's simple enough
to implement.

This is the approach I use:

I have a base class derived from System.Web.UI.Page and override Render

namespace DoNot.Invade.MySpace
{
class Page : System.Web.UI.Page
{
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);

base.Render (hw);

string html = sb.ToString();

html = html.Replace(Environment.NewLine, string.Empty);
html = html.Replace("\n", string.Empty); // This may be redundant
html = html.Replace("\t", string.Empty);

writer.Write(html);
}
}
}

You'll want to be careful with simplistic code like this. There are
times when whitespace and newlines are significant, such as text inside
 
True, I guess I should have mentioned that. Since the site I'm currently
working on doesn't use <pre> I don't worry about it. And what I have written
can be expanded upon to handle these situations.

There are other cases where this is a problem too. Such as the following:

<p>
This is
some text
</p>

will produce the following output:

This issome text

For me, though, I just edit the html and make sure there is also a space
before the newline.

Regards
Brian W
 
Back
Top