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”).

2 comments:

  1. Oh, man, how I hate Google Analytics' default code. Always have. The
    unnecessary usage of all those functions when it would suffice just to give a plain old <script
    src=""> with a checkbox on the page to specify if SSL support is needed.

    But even
    if I hate the default code, they should make it more DOM-compatible. document.write is not a very good way
    to be doing things any more.

    ReplyDelete
  2. It really isn't. As far as I remember, Google Adsense isn't very W3C or
    DOM friendly either.

    It's a damn shame.

    ReplyDelete