Blogger Blogs, Ga.js, And XHTML

December 18, 2007
By

  If you’re having trouble getting the new Google Analytics, ga.js code to work on
  your Blogger Blog, we have a quick and easy fix for you.

  Actually, this fix isn’t specific to Blogger or even Google Analytics for that matter. 
  To make your web pages XHTML-compliant, you should either do this on all of your
  scripts, or you should move your scripts to a separate file.

  Here’s an example: (Beware of smart quotes.  WordPress keeps changing my formatting automagically.)

<script type=’text/javascript’>
//<![CDATA[
var gaJsHost = ((“https:” == document.location.protocol)
? “https://ssl.&#8221; : “http://www.&#8221;);
document.write(“<script src='” + gaJsHost
+ “google-analytics.com/ga.js’ type=’text/javascript’></script>” );
//]]>
</script>

<script type=’text/javascript’>
//<![CDATA[
var pageTracker = _gat._getTracker(“UA-XXXXXXX-1”);
pageTracker._initData();
pageTracker._trackPageview();
//]]>
</script>

See how the first line after each script tag, we have: //<![CDATA[

And right before closing each script tag, we have: //]]>

The forward slashes are JavaScript comment indicators for older browsers that don’t understand CDATA.  This post on About.com provides some additional information.  Note the author uses multiline comment characters rather than the // we use here.  Both methods will work just fine.

So what have we done?

  We told the browser’s validator to ignore our script by wrapping it in the CDATA
  tag.  So now Blogger and the W3C will happily accept your Google Analytics
  Tracking Code.

  – Jason Green