Wednesday, February 13, 2008

Google Analytics Tracking Code Does Not Validate

A while back, Google switched it's Analytics tracking code from Urchin.js to their own GA.js code. If you are an older subscriber to Google Analytics, you have the option of using the old Urchin code or the new and improved GA code - which promises better tracking stats and other new features as they become available.

There's just one catch. The new code does not validate in XHTML. It doesn't publish correctly within Blogger templates. And some web developers say it doesn't work in ASP websites.

Given that Google recommends using valid X/HTML to promote better search ranking and improved user accessibility, one would think the code they provide for use on millions of web sites should validate. Fortunately, there is a relatively easy fix by inserting CDATA tags (shown in red text) to your tracking code.

XHTML compliant version of the GA.js code:

<script type="text/javascript">
//<![CDATA[
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
//]]>
</script>
<script type="text/javascript">
//<!--[CDATA[
var pageTracker = _gat._getTracker("UA-XXXX-XX"); pageTracker._initData(); pageTracker._trackPageview();
//]]-->
</script>

That's all there is to it.

2 comments:

Anonymous said...

If it is that easy why doesn't Google just update their code per this suggestion? Do you have and explaination for us non-programmers what that added tag is doing?
Thanks

Nancy O. said...

You should ask Google why they don't fix their code.

XHTML pages behave differently than HTML pages. If you insert Javascript into an HTML page, the validator treats everything after the script tag as CDATA (character data) and ignores it.

In XHTML, JavaScript is considred PCDATA (parsed character data) and thus doesn't validate.

Inserting the CDATA tags into your Javascript code effectively tells the validator to ignore the code so the page won't 'break' or fail validation.