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
?
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With