Dynamically loading Google Analytics

I finally finished the Creative Industries Newswire website. The Creative Industries Newswire is a centralized place where authorized QUT staff members can author and publish news items. It is a place where users can access those news items, leave comments, and subscribe to individual news wires via RSS. It basically runs off WordPress.

Creative Industries newswire homepage.

A few interesting issues that emerged with relation to using Google analytics. The issue with this website is that it is used by both public users and users on an intranet. Intranet users at QUT may be authenticated to access resources on the intranet (such as the newswire website), but not resources on the internet. When an unauthenticated users tries to load a page with the following Google-provided code the browser attempts to load the script but eventually times out. This can take around to 60 odd seconds in Firefox (or something close to that, not sure exactly how long). The implication is that, to the user, the browser looks as if it is still loading content. And in the browser, it does not execute the
<script> tags. Below is the problematic code that Google provides:

<script src="http://www.google-analytics.com/urchin.js"  type="text/javascript">
<script type="text/javascript">
   _uacct = "UA-XXXXXX-1"; urchinTracker();

Looking at the code above, what essentially happens is:

  1. urchin.js needs to load synchronously and block the second script tag from running
  2. once loaded, the code inside the second script element must be run
  3. if the code is run without the script first loading, then the urchinTracker() method will be undefined.

So, like I already stated, in the intranet scenario, the urchinTracker() method is never called because urchin.js is never loaded. To make the whole process a bit more “behind-the-scenes” I decided to recode the Google code so that it is run only once the document has executed it “onload” function. The following simply dynamically appends the DOM with a script element AFTER the document has loaded. If the script element can reach its src, then analytics info is sent to Google, otherwise, nothing happens:

window.onload = function(){
   var scriptLoadFunction = function(){
   _uacct = "UA-XXXXX-X";
var e = loadScript("https://ssl.google-analytics.com/urchin.js", scriptLoadFunction);

function loadScript(url,aFunction){
var e = document.createElement("script");
}else{ //try to force IE to work, but alas, it does not.
e.src = url;
return e;

The code works great in Firefox 2.0 but does not work in IE6 or IE7 (as IE does not support the addEventListener() function). If anyone has a work around to this problem, I’ll like to hear about it.

5 thoughts on “Dynamically loading Google Analytics”

Comments are closed.