Augustin Riedinger
Augustin Riedinger

Reputation: 22238

Insert Front-End Library (eg. Analytics): why not a simple <script> tag?

In order to insert GA code (and pretty much any other JS library), the code snippet is:

<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-X', 'auto');
  ga('send', 'pageview');

</script>

Why not:

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

at the end of the body?

Upvotes: 9

Views: 151

Answers (4)

Alex
Alex

Reputation: 4934

Google knows that the script they have is not dependent on any other script in the page, therefore they are enforcing that the script is executed as 'non-blocking' meaning that the script content is executed ASAP, outside of the usual tag ordering within the document (it does not have any dependencies).

The implementation of the DOM script tag is non-trivial and must cater for script inter-dependencies, unless explicitly stated as 'async'. In this case the external code will be executed immediately, without waiting for anything else on the page to load.

Google have documented their approach well here. Basically it will improve performance on old browsers by allowing async script execution. Dynamically inserting a script tag mimics the behaviour of the native async attribute in modern browsers. You can see that the dynamic script tag is marked as async in their code injector function, to cater for modern browsers too.

i.e. a.async=1;

Upvotes: 1

Francis Nepomuceno
Francis Nepomuceno

Reputation: 5085

According to Google's docs, they do recommend the simpler <script src> version but only if you're targeting modern browsers (excluding IE 9).

Upvotes: 1

som
som

Reputation: 2477

As has been mentioned in the comments, Google are simply providing an idiot-proof script block with maximum browser support.

Specifically, the async attribute isn't supported in IE9. See http://caniuse.com/#search=script-async

Upvotes: 3

Corey Young
Corey Young

Reputation: 570

The first reason is for some scripts they need to run before the html is created, and the second for it not to be in an external script is that you need to overwrite some values.

 ga('create', 'UA-XXXXXX-X', 'auto');

you have to put your own GA account here so it makes no sense to put such a short script inside a an external file. It is done this way for ease of use so that even beginner devs and non devs can add analytics to a page.

Upvotes: 0

Related Questions