4

Why do I need to use:

(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);
})();

Instead of:

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

The only reason I can see is that they have a different subdomain for SSL. If it weren't for that is there any reason to use this script injection technique?

1 Answer 1

6
  1. Being able to serve out http or https depending on the protocol of the parent page is one reason.

  2. As the script is injected via a script tag inserted via running JS code, it does not block page loading. This is another reason. But this can very well be achieved via the new HTML5 async attribute too (but this is not compatible with older browsers - and GA absolutely needs to be compatible with pretty much all of them)

8
  • 4
    Primarily point #2 (and the subdomain). Point #1 could be solved by just starting the URL without a protocol (... src="//www.google-analytics.com/ga.js" ...). Commented Feb 11, 2013 at 15:43
  • @T.J.Crowder - Yes, that is also correct, but will it work for all browsers including older ones. Bcoz GA has to be super compatible with all i imagine.
    – techfoobar
    Commented Feb 11, 2013 at 15:44
  • Also, location.protocol can be used to dynamically detect the right protocol.
    – marekful
    Commented Feb 11, 2013 at 15:44
  • @techfoobar: Compatible with anything you want to throw at it, see the link I added. :-) Commented Feb 11, 2013 at 15:46
  • @T.J.Crowder - Thank you for the informative article. So this in combo with async should mean no more script, maybe few more years down the line..
    – techfoobar
    Commented Feb 11, 2013 at 15:47

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