Sunday, April 4, 2010

Making Google Analytics Work in XHTML

I was moving my website, Google Voice for Outlook, over from HTML5 to XHTML5 today, and
as soon as I did the basic content negotiation filters in PHP so that it would send the appropriate headers
if the client supported XHTML as well as only outputting the <?xml if the client supported XHTML, I
checked my developer tools to find a JavaScript error.  It was Google Analytics, of course.  document.write
doesn’t exist in XHTML, after all.

The fix was simple, replace the current four line
inclusion code with:
[codesyntax lang="javascript"]<script
type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ?
"https://ssl." : "http://www.");
var script = document.createElement("script");

script.src = gaJsHost + "google-analytics.com/ga.js";
script.type = "text/javascript";

document.getElementsByTagName("head")[0].appendChild(script);
</script>[/codesyntax]

This
will work fine, unless of course you have no head tag.  In which case you should replace
getElementsByTagName(“head”) with getElementsByTagName(“html”).