Slow loading with Google Analytics

I experienced my pages slowing down when using Google Analytics togheter with my Firefox AddOn NoScript. Since I’m far from the only one using NoScript I found this not acceptable and worked out a possible work around.

The reason for the slow down is likely the timeout of the connection between my domain (where I’ve allowed scripts to run) and Googles domains (where I might or might not have allowed scripts).

Googles code look like this (where “UA-1111111-1” is your tracking ID):

<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src='” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
var pageTracker = _gat._getTracker(“UA-1111111-1”);
pageTracker._initData();
pageTracker._trackPageview();
</script>

The first part of the code creates an obfuscated loading of the script located at google-analytics.com/ga.js. It picks a prefix of www if it’s a standard connection and ssl if it’s  an encrypted connection. The problem is that NoScript does not recognize this code and ends up in a deadlock of wether or not to allow the script to be run. My guess is that there is another script loaded from another domain called googlesyndication.com which fails to enter the NoScript-test and locks the loading of the page.

A possible fix that I’m still evaluating but which should do the trick is the following (code in bold added):

<script src=”http://www.google-analytics.com/ga.js” type=”text/javascript”></script>
<script type=”text/javascript”>
var pageTracker = _gat._getTracker(“UA-1111111-1”);
pageTracker._initData();
pageTracker._trackPageview();
</script>

As you can see I’ve made the obfoscated code clear text code and chosen the http://www-prefix (since I’m not using an encrypted connection for my server). Should you use encryption on your site simply switch http://www to https://ssl instead (this is what the javascript used to do). If you have a page which might be loaded encrypted or normally then you would have to include this choice earlier in a server side script for example.

After this fix Google Analytics works like a charm togheter with NoScript on any script-level setting for me.

Try this at your own risc, this is still experimental to me as well!