Google Analytics XHTML compliance

6 Jun
2008

I had to add the Google Analytics code snippet to this site and had some issues with it validating as XHTML 1.1 and MIME type application/xhtml+xml which were solved at the end.

The snippet is divided into two pieces of <script> tags and the first part is simply a feature to avoid getting warning messages from your browser if your page was server over SSL (https://). If your site serves pages in both HTTP and HTTPS then you can achieve the same through e.g. a server side scripting language such as PHP.

The snippet needs to be changed to the following on HTTP pages:

<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>

and of course on HTTPS pages use this piece:

<script src="https://www.google-analytics.com/ga.js" type="text/javascript"></script>

Now the second part of the code needs to be put between CDATA tags to properly isolate it. The code will now look like this except you need to introduce your own Google Analytics ID:

<script type="text/javascript">
//<![CDATA[
var pageTracker = _gat._getTracker("UA-1234567-8");
pageTracker._initData();
pageTracker._trackPageview();
//]]>
</script>

Now you can safely run the W3 Validator without any errors caused by Google Analytics.

4 Responses to Google Analytics XHTML compliance

Avatar

Magnus

August 18th, 2008 at 02:55

Thanks for the info in this post, it was helpful compared to some other articles which only went halfway.

FYI, it seems like pageTracker._initData(); is not needed anymore, it was not part of the tracking code the GA tool outputted to me just now.

Avatar

mr-euro

August 19th, 2008 at 18:52

@Magnus

Thank you for the notice. It does seem that Google Analytics recently changed their tracking code snippet a bit, although it does not affect the running of the old code.

Avatar

Mike LLIA

April 30th, 2009 at 21:51

Good info but my issue with google analytics code and XHTML validation is where the placement of the js(Google recommends after the body tag), I get this error:
document type does not allow element “script” here

Avatar

mr-euro

May 11th, 2009 at 19:14

@Mike LLIA

I think putting the code after the body tag is incorrect and therefore the validation fails.

I place the Google Analytics code just before the closing body tag.

Comment Form

top