简体   繁体   中英

Can I put Google analytics in external JS?

<script type="text/javascript">

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

Apart from caching issues (if I change my tracking ID), is there anything else I need to be aware of? Will it still function? It recommends putting it before </head> , all my other JS is before </body> , is it ok to put it there?

Besides potentially needing to change the tracking code, the only potential issue I can think of is that, in the scheme of things, visitors who leave between when that file is requested and when it arrives will not be tracked. Or, if for some bizarre reason, the external script fails to load, you will not have tracked that user. Besides that, you're safe to include it in an external script.

All this code really does is find the first script element in the DOM and puts a new script element just before it. The new script element is pretty much equivalent to:

<script type="text/javascript" async src="https://ssl.google-analytics.com/ga.js">

on HTTPS pages, and:

<script type="text/javascript" async src="http://www.google-analytics.com/ga.js">

on HTTP pages.

It works fine anywhere in the page, in head and in body. Also it doesn't slow down your page rendering if it is in head so it doesn't really matter where you put it.

The only difference is that when you have it in the head then you can easily connect your Analytics account with Google Webmaster Tools for that page and if it's in the body then you have to use some other form of verification to prove that it is your website.

Putting it in an external file would mean one more HTTP request if it is not in the cache and potentially would save just few lines of code if it is in the cache, but then you can't easily change the tracking ID for any given page.

Other than that I would be careful with putting it in an external script because it may be against the terms of service.

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