Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 447
Augustin Riedinger Avatar asked Jun 26 '15 13:06

Augustin Riedinger


Video Answer


2 Answers

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

like image 194
som Avatar answered Oct 24 '22 19:10

som


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;

like image 40
Alex Avatar answered Oct 24 '22 19:10

Alex