One of the things that have always seemed a little weird to me is that ASP.NET auto-generates JavaScript and injects it in the rendered HTML. The JavaScript is needed to handle validation, postbacks, callbacks etc. but why does it have to write the same static functions when it could just as well be placed in a referenced .js file? If all the static functions where placed in an external .js file, it would be downloaded once instead of every time a page loads.
I thought I’d do something about it and wrote an HttpModule that removes and rewrites some of the auto-generated JavaScript. Then I put the static functions into an external .js file and referenced that from the <head> section instead. It also changes all document.getElementById(id) to $(id).
The result is a smaller and cleaner HTML output
I’ve implemented it on this website and if you take a peek at the HTML source you’ll notice that you don’t find functions such as __doPostBack and ValidatorOnSubmit along with some other JavaScript logic. It has been moved to my global external .js file instead.
Implementation
Download the zip file below. It holds two files – an HttpModule and a JavaScript file. You need to reference the .js file or copy the contents into your own external referenced .js file. Then hook the HttpModule up in the web.config.
CleanPage.zip (1.63 kb)
By coincidence I noticed a method I’ve never seen before on the ClientScript property of the page class in ASP.NET 2.0. It’s called something as cryptic as RegisterExpandoAttribute and it’s very useful.
It can set JavaScript properties on any element you would normally reference with document.getElementById(‘elementID’). That means you can control the state of your HTML elements from the code-behind in a very easy manor. It also means you can control HTML elements that don’t have a runat=”server” attribute.
Here are two examples – one where a property is set on a server-control and one on a HTML element otherwise invisible to the code-behind.
Page.ClientScript.RegisterExpandoAttribute(txtPassword.ClientID, "value", "britney");
Page.ClientScript.RegisterExpandoAttribute("maintable", "background", "red");
And this is the JavaScript it produces:
<script type="text/javascript">
<!--
var txtPassword = document.all ? document.all["txtPassword"] : document.getElementById("txtPassword");
txtPassword.value = "britney";
// -->
</script>
I think where this really rocks the most is the ability to control regular HTML elements that hasn’t got the runat=”server” attribute. Those elements have always been invisible to the code-behind and now you have direct server-side access to their properties. The method doesn't give you anything you couldn't do before, but it makes it so much easier and cleaner.