views:

39

answers:

3

New Google Analytics code looks like one below:

<script type="text/javascript">

 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-0000000-00']);
 _gaq.push(['_trackPageview']);

 (function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();

</script>

How to move the whole new Google Analytics Asynchronous Tracking Code into an external JavaScript file?

I'm asking especially about "var _gaq = _gaq || []; [...]" part because I know it's possible to move the rest e.g.

index.html

<script type="text/javascript">

 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-0000000-00']);
 _gaq.push(['_trackPageview']);

</script>
<script src="include.js" type="text/javascript"></script>

include.js

function includeGA()
{
 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
}

$(document).ready(function()
{
 includeGA();
});

I've already tried to place the "var _gaq = _gaq || []; [...]" code into various locations but nothing worked.

A: 

I don't see why you can't put it above "function includeGA()" in the include.js. Actually, I don't see why you can't copy the whole google script literally into the include.js (without the $ workaround). This should be inlined by the script-include tag, right?

Jochem
A: 

This appears to be a similar question to this one: http://stackoverflow.com/questions/3263818/using-google-analytics-asynchnonous-code-from-external-js-file

It seems pushing the code into an external file removes the benefit of the new asynchronus code.

MrG
A: 

Then again: don't put your Google Async snippet in an external file because it will block other contents from downloading. The main point of having an asynchronous tracking code is to make it parallel.

If you use the asynchronous GA just put it in the top of you document in an inline script tag. This is the recommendation on Google Analytics website as well:

Insert the asynchronous snippet at the bottom of the <head> section of your pages, after any other scripts your page or template might use.

galambalazs