1

When one wants to include Google Analytics in his website, here is the code he has to include:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXX-1', 'auto');
  ga('send', 'pageview');

</script>

Why this is not simply

<script src="http://www.google-analytics.com/analytics.js?id=UA-XXXXXX-1" async></script>

?

2 Answers 2

1

Because it does more than that. But indeed, you could use

<script>
window.GoogleAnalyticsObject = "ga";
window.ga = window.ga || function() {
    if (!window.ga.q) window.ga.q = [];
    window.ga.q.push(arguments)
}
window.ga.l = +(new Date);
ga('create', 'UA-XXXXXX-1', 'auto');
ga('send', 'pageview');
</script>
<script src="http://www.google-analytics.com/analytics.js?id=UA-XXXXXX-1" async></script>

They just don't because that's two scripts instead of one, and dynamically creating the script ensures asynchronous loading even in browsers that don't understand the async attribute.

4
  • But the first script could be in the second one, no?
    – Arnaud
    Jul 12, 2015 at 21:13
  • 1
    @Arnaud: Not if you intend to call ga() synchronously before the script was loaded. It's not necessary for those two create and send calls indeed, but IIRC all kinds of ga() calls are used in some sites, placed just right below the include script. ga needs to be declared immediately to start registering calls.
    – Bergi
    Jul 12, 2015 at 21:17
  • Ok, so the only purpose is to allow websites to make custom calls to Google Analytics? (and to support the 10% of browsers that don't understand async)
    – Arnaud
    Jul 12, 2015 at 21:24
  • 1
    Yes, basically. Also, ga.l seems to be immediately initialised with a timestamp before the script is loaded, so that GA can measure some things based on that.
    – Bergi
    Jul 12, 2015 at 21:32
1

Because it is non-blocking this way. When the browser loads the page, it loads all of the resources and scripts.

With google's inline function, it inserts the script after the page has been loaded so the page load time is not increased.

Also, the async attribute is not supported by all browsers.

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#Browser_compatibility

2
  • It is supported at 90% (caniuse.com/#feat=script-async). If it was at 100%, would it be a good idea for Google to switch to my solution?
    – Arnaud
    Jul 12, 2015 at 21:14
  • Not necessarily, you still have to have a script to send the page view. A lot of people customize their page views to attach additional data such as user type. Jul 12, 2015 at 22:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.