It’s no secret that Google Analytics had become one of the most prevalent statistics and tracking offerings on the net. In the acquisition of Urchin and making the analytics software freely available, Google has provided web developers and content providers alike with an immensely powerful tool to track visitor capabilities and browsing trends, in a way that wasn’t possible just a few short years ago.

Unfortunately for us web developer types, the default code simply doesn’t work with the latest web standards, namely XHTML 1.1. While it may work with earlier transitional versions of XHTML, it chokes when it’s included in a properly validating XHTML 1.1 page because of the use of some fairly questionable techniques.

The main problem we face is that the script uses the unsupported document.write method to insert a <script> element into the document, which will do exactly nothing in a proper XHTML page. Ideally we should be using document.createElement to insert such an item, but for this purpose it’s really overkill. Here’s why:

Remove the document.write

If we look closely at the ga.js sample code Google Analytics gives us, we can see that the first half of the script is performing a simple conditional query to determine whether or not our page is being served over insecure http or secured https.

If we work through the code, we can easily remove the Javascript condition and turn the script into a plain old external javascript which is perfectly acceptable in the world of the XHTML DOM.

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

Return SSL Support

The above script will now be perfectly usable for our regular http transactions, but what about pages delivered over ssl?

The browser will throw an error complaining that some of the items on the page are being delivered insecurely, so we’ll need to adjust the script accordingly.

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

Contextual Loading

We can do this manually by including the separate scripts in the relevant locations, or we can use PHP to simplify the process for us. The following script will dynamically decide whether to display the secured version or the plain version depending on the page context.

<script type="text/javascript" src="http<?php if($_SERVER['HTTPS']) echo 's' ?>://www.google-analytics.com/ga.js"></script>

While plenty of neater solutions exist, this is a simple cut & paste script that you can use in your own projects. Just make sure to include the second part of the tracking code as is, and everything should start working in your valid XHTML pages.

Enjoy your newfound, and completely valid Google Analytics code.


Recent Posts

Post a Comment

Your email is never shared.

*
*