20 April, 2010

Ban HTML comments from your pages and views

Ban HTML comments from your pages and views:

Too many people don’t realize that there are other options than <!-- --> comments to annotate HTML. These comments are harmful because they are sent to the client and thus make your page heavier than it needs to be.

Replacing client comments with server comments.When doing ASP.NET, a simple drop-in replacement is server comments, which are delimited by <%-- --%> instead of <!-- -->. Those server comments are visible in your source code, but will never be rendered to the client.

Here’s a simple way to sanitize a web site. From Visual Studio, hit CTRL+H to bring the search and replace dialog.

Choose “Replace in Files” from the second menu on top of the dialog. Open the find options, check “use” and make sure “Regular expressions” are selected. Use “*.aspx;*.ascx;” as the file types to examine. Choose “Entire Solution” under “Look in”.

Here’s the expression to search for comments:

\<!--{[^-]*}--\>

And here’s the replacement string:

<%--\1--%>

I usually use the “Find Next” and “Replace” buttons rather than the more brutal “Replace All” in order to not apply the fix blindingly. Once this is done, I do a second manual pass of finds with the same expression to make sure I didn’t miss anything.

No comments:

Post a Comment

Suggestions are invited from readers