views:

147

answers:

4

I've seen this in a few pieces of code and I didn't want to "assume" it was unimportant but this is a copy of the Google Analytics code:

<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-xxxxxx");
     pageTracker._trackPageview();
    } catch(err) {}
</script>

You'll notice there are two open / close script tags. Is there any reason why encapsulating the code bits in two different script tags is beneficial? My first reaction would be simply to remove the redundancy.

A: 

I guess the two script blocks were created by different source modules (classes/objects/whatever).

erikkallen
A: 

The most likely reason the page has two script tags is because two separate modules of the system both wish to add javascript functionality to the page, but want to ensure that it inserts itself cleanly.

If they were authoring the page as a single, static page, one script tag would be fine. Since the page is likely dynamically generated, don't worry about it so much.

Randolpho
+5  A: 

The first block writes a <script> tag to the page. I think if the code was all in one block there would be no guarantee the written <script> would be loaded before the second part of the code executed.

By using two blocks, the written <script> will load (which contains the _gat object) before the second block executes.

Greg
A: 

If an error occurs in the first script tag, the second one will still execute.

If the second one relies on the first one, however (eg, if it uses functions defined in the first one), it might still fail. (Because the first one didn't fully execute)

SLaks