Insert Google Analytics code

GAAdd was a javascript function that automatically added the original google analytics code to your pages using DOM methods. Unfortunately the new google analytics code doesn’t seem to work with it. Below is another method which uses PHP and our attempt at making the new code work.

What happened to GAAdd

When Google came out with it’s updated version of the google analytics code we tried adding it with DOM methods and were having a timing issue with the loading of the page that kept the code from working. Instead of spending a lot of time fixing it we’ve decided to instead just use a PHP include to put the code into our pages, which we’ll talk about in a second.

The main advantage of the old GAAdd javascript function over just adding the code yourself to the pages (or even with a server-side include) is that if javascript wasn’t active the code wouldn’t be in your pages. Personally I think that any code that relies on javascript should be added with javascript.

The PHP Include

The easy way to include the code into all your pages is with a php include (if you’re using .php pages). You’d just make a separate file (I put mine in an includes/ directory) and call it gaadd.php

Then at the bottom of all your pages you’d put this line just before the </body> tag:

Where We Left Off With the Javascript

In case anyone with better DOM scripting skills than me (I’d say I’m past beginner, but not yet intermediate) is interested in fixing this script please let me know where the problem is, I’d still be interested in using it, but it’s a bit beyond me at the moment.

I was adding it to every page through a global.js file which had Simon Willison’s page load event calling the function. I’m pretty sure the problem lies in the line that uses document.write to write the third script tag, since they are not getting written into the page it’s probably something to do with the fact that I’m adding this stuff after the DOM is completely loaded? Not sure really.

Enable Javascript