Sunday, December 16, 2007

New Google Analytics Code breaks valid HTML

Et tu, Google? ;)

When I get sick, I tend to do two things: sleep a lot and catch up on coding articles that I never get to read otherwise. So, when I learned that Google Analytics (the service I use to track visitor stats for this blog) had released new tracking code, I decided to remove the legacy code and drop in the new stuff.

And, because I'm gradually becoming OCD about web standards in my new job, I made sure to run the W3C's HTML Validator tool against it. Yup, you guessed it, the new code breaks valid HTML. Seven errors if you place it near the tail end of your document, like GA's documentation suggests, or 29 errors if I put it in the head portion of my blogger template.

After some experimenting, I think I found a way to include the code so that it doesn't throw errors in a validator. I need to make sure the code is working properly by checking my visitor data in the next day or two, but I think this should work. The trick is to use HTML comment tags after each opening script tag and before each closing script tag. Like so:

<script type="text/javascript">
<!--
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write("\<script src="'" type="'text/javascript'">\<\/script>" );
-->
</script>
<script type="text/javascript">
<!--
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._initData();
pageTracker._trackPageview();
-->
</script>

Yeah, I know. Most people won't care. If you do, though, and this saves you time, you're welcome.