views:

443

answers:

2

Why does the Google Analytics script I add to my webpage need to come in two script blocks?

<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-xxxxxxx-xx");
        pageTracker._trackPageview();
    } catch (err) { } 
</script>
+18  A: 

The first script in your quote above writes a new <script> loading tag into the document. The second block has dependencies that are loaded by that dynamically written script tag, so the browser has to have a chance to load and parse the script before the second block runs. If everything was in one block, the script loading wouldn't take place until the first script section ended.

Jarret Hardie
+1. Specifically, the dependency is the _gat._getTracker(...) line.
John Feminella
+1  A: 

You may now wish to use the latest update to Google Analytics. This offers performances improvements, enhances data collection and prevents tracking code errors.

James