title: Using Google Analytics asynchronous code from external JS file
body: <p>I'm trying to add the asynchronous version of the Google Analytics tracking code to a website.</p>
  
  <p>I'd like to keep the JavaScript in a separate file, and call it from there.</p>
  
  <p>Here's what I've currently got in my .js file:</p>
  
  <pre><code>function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
          window.onload = func;
      } else {
          window.onload = function() {
              oldonload();
              func();
          }
      }
  }
  
  function loadtracking() {
      var _gaq = _gaq || [];
          _gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
          _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);
          })();
  }
  
  addLoadEvent(loadtracking);
  </code></pre>
  
  <p>And here's what I've got in the <code>&lt;head&gt;</code> tag of my Master page:</p>
  
  <pre><code>&lt;script type="text/javascript" src="js/google-analytics.js" &gt;&lt;/script&gt;
  </code></pre>
  
  <p>However, there's obviously a problem as after a few days, I'm not getting stats through!</p>
  
  <p>Any ideas what I need to change?</p>
  
  <p>Thanks,
  Neil</p>
  
  <hr>
  
  <p><strong>EDIT:</strong> Ok... After some feedback below, I'm going to add the <em>new</em> current contents of my .js file. I'll keep it updated so that if/when this gets solved, it will hopefully help other people trying to do similar things.</p>
  
  <pre><code>var _gaq = _gaq || [];
  
  function loadtracking() {
          window._gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
          window._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);
          })();
  }
  
  loadtracking();
  </code></pre>