What is the recommended way to add Google Analytics code and why?

I read in many sources that Google's recommended way to add GA code ( link ) can slow down page loading. StackOverflow itself does not place it in the header (as Google recommends), but at the bottom of the page.

So should I go with Google, StackOverflow & mdash or use jQuery getScript?

+3
source share
7 answers

Google Analytics recommends placing an asynchronous fragment immediately before the tag </head>.

<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>

</body>, . .

, script , JavaScript, . , ga.js Google, __utm.gif Google .

script , . , , , . , , .

, Google Analytics URL- ( Google HTTP HTTPS), , , , , , script .

, , </head>.

+6

"" Google, . Google , </body>.

, <head>

, () Google <head> .

+1

jQuery . Google , jQuery. :

Google Analytics -fuzz jQuery https://github.com/mekwall/jquery-ga

+1

<body>.

:.

  <script>
   var _gaq = [['_setAccount', 'UA-xxxxxxx-1'], ['_trackPageview']];
   (function(d, t) {
    var g = d.createElement(t),
        s = d.getElementsByTagName(t)[0];
    g.async = true;
    g.src = ('https:' == location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    s.parentNode.insertBefore(g, s);
   })(document, 'script');
  </script>
</body>
+1

$. getScript, URL-, . , , . ( "on" .)

http://blog.yjl.im/2010/09/jquerify-google-analytics-tracking-code.html

- . , javascript Google.

$.ajax(('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js', {dataType: 'script', cache: true})

Also note that this will soon be replaced by the universal isogram analytic code.

+1
source

As explained here:

https://developers.google.com/analytics/devguides/collection/gajs/#SplitSnippet

If your pages load slower (mine, of course, were), you can split the code into two parts by placing the first in <HEAD>

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXX-X']);
  _gaq.push(['_trackPageview']);
</script>

and the second at the foot, a little higher </body>

<script type="text/javascript">
  (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>

After that, my pages load as quickly as possible.

0
source

Source: https://habr.com/ru/post/1784272/


All Articles