Alex Rivera | Logout

New Google Analytics code into external file

Asked 2010-10-06T07:39:48.860
17

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.

Edit
Report

1 Answer

20

You shouldn't put GA code in function for two reasons:

  1. The variables of GA become local. They need to be used globally.
  2. You're calling the function only when the whole of page (document, technically) is loaded. This makes the download process serial (defeating the parallelism of asyn analytics).

People criticizing the use of external JS for GA code, are bit wrong here. With introduction of async attribute in js embed, it makes sense. I keep this GA code in external js and embed it async right in the head of document. Two benefits:

  1. Keeps the code neat (no inline GA)
  2. Caches the js- saves bandwidth & loads faster

So the HTML would become:

<head>
    <script type="text/javascript" src="static/scripts.js" async></script>
</head>

and scripts.js will have:

var _gaq=_gaq||[];
_gaq.push(['_setAccount','UA-XXXXXXXX-1']);
_gaq.push(['_setDomainName','.domain.net']);
_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)
})();
answered 2012-10-29T13:58:00.147

Your Answer