19 September 2006

Moving ViewState to the Bottom of the page

I was researching some weird ViewState bugs today and stumbled across this post on moving the ViewState to the bottom of the page. The main point of this is SEO; I seem to recall that Google (and possibly other search engines) only read the first xkb of a page, so when a page has a fair few kb of ViewState on it this can screw up your SEO and mean information you want indexing doesnt.. (get..)

Enter Scott's method. It's pretty straightforward really, you're just physically moving the field to the just before the end of the form tag. The one problem I have with his method is that with .NET 2.0 in XHTML compatibility mode the ViewState field is wrapped in a <div> tag as you're not allowed <input> elements in the root of a form tag. Scott's method breaks this convenient addition by moving the __VIEWSTATE input field out of the div, what we ideally want is the dv moving too, hence I came up with a new version of the Regular Expression he uses:

(<div>[^<]*<input.*name="__viewstate"[^>]*>[^<]*</div>)

All pretty straightforward, you may notice that I chose to strip out the type="hidden" part of the original Regex so as to make things a bit more more generic. I havent delved into the (faster) non-Regex method Scott outlines as I personally think the Regex method is more readable - feel free to give it a try if you like.

No comments: