Two separate script tags for Google Analytics?
google-analytics, javascript
Solution
`<script>` tags are executed in sequence. A `<script>` block cannot execute if the previous one isn't done executing.
The first `<script>` tag is in charge of creating the Google `<script>` tag which will load the external js. After the first `<script>` is finished executing, the DOM looks like the following:
<script></script> <!-- First Script Tag -->
<script></script> <!-- Google Injected Script -->
<script></script> <!-- Second Script Tag -->
This guarantees that the second `<script>` tag will not execute until the `.js` is done loading. If the first and second `<script>` would be combined, this would cause the `_gat` variable to be undefined (since the Google injected script will not start loading until the first script is done executing).
Problem
Does anyone know why Google Analytics requires two separate script tags? Specifically, their instructions advise users to embed the following snippet of code into a web page for tracking purposes: ``` <!-- Google Analytics --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-8720817-1"); pageTracker._trackPageview(); } catch(err) {}</script> ``` Why couldn't users use only one script block like this: ``` <!-- Google Analytics --> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); try { var pageTracker = _gat._getTracker("UA-8720817-1"); pageTracker._trackPageview(); } catch(err) {}</script> ```