简体   繁体   中英

Where should I put the Google Analytics asynchronous snippet

Google says

The asynchronous snippet should appear at the top of your page before the closing tag.

And gives this:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-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);
  })();

</script>

Can I make that an external .js file, or does it have to be in the html page itself?

The snippet can be loaded in any way. If you want to include it in an external file, knock yourself out. Google recommends putting it in the <head> to maximize the number of pageviews that get tracked, but you could just as easily load it in the <body> without trouble, or from an external JavaScript file, or even a dynamically injected JavaScript file. All that needs to happen is that the snippet needs to execute; ga.js takes care of the rest.

Even if your browser caches the code itself, it will still execute ga.js (which itself may be cached), but the data it sends to Google Analytics is very heavily cache busted. There's no way your browser could cache that request, even in the strictest of proxy environments.

The way your analytics data gets "sent" to Google Analytics is that ga.js , after gathering all of the analytics data from the environment, your configurations and the cookies it sets, concatenates all of those values onto a query string on a dynamic image request (requested via JavaScript and never actually injected into the DOM.) Those requests feature cache-busting parameters, as well as data that is generally unique to each request.

Further, the image that is requested specifically instructs the browser to avoid caching it by setting these headers:

Cache-Control:private, no-cache, no-cache=Set-Cookie, proxy-revalidate
Expires:Wed, 19 Apr 2000 11:43:00 GMT
Pragma:no-cache

The snippet must be on the page itself.

\n

If the snippet is in an external JS file, the browser will cache the file and the snippet would generate hit only the first loaded page from your site.

There are more delicated ways to call the snippet API from Javascript if needed - these are mainly used for track special events, like button presses, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM