views:

229

answers:

3

Duplicate of

Any value in double script tags?

Here's a code snipped from UserVoice in order to stick their tab on my site (this isn't specific to UserVoice however, I see this kind of thing all the time):

<script type="text/javascript">
    var uservoiceJsHost = ("https:" == document.location.protocol) ? "https://uservoice.com" : "http://cdn.uservoice.com";
    document.write(unescape("%3Cscript src='" + uservoiceJsHost + "/javascripts/widgets/tab.js' type='text/javascript'%3E%3C/script%3E"))
</script>
<script type="text/javascript">
    UserVoice.Tab.show({
        key: 'wikipediamaze',
        host: 'wikipediamaze.uservoice.com',
        forum: 'general',
        alignment: 'right', /* 'left', 'right' */
        background_color: '#94C97B',
        text_color: 'white', /* 'white', 'black' */
        hover_color: '#7AA1C5',
        lang: 'en' /* 'en', 'de', 'nl', 'es', 'fr' */
    })
</script>

How this can't all be jammed into one script tag and put into a separate file? Any time I try do it, it doesn't work. Google ads does the same kind of thing. Why are there 2 separate script declarations?

A: 

JavaScript gets executed as it is loaded so the position of the script on the page may have some importance. It really depends on the page and the script.

Also, it is very common for web components and libraries to have their own scripts, so if you have many components on a page they could all have separate scripts tags for their individual scripts.

Ryan Cook
A: 

In this case, at least to me, it just reads better. The first script tag is dynamically loading a script from their servers. The second script tag is actually doing the work. Think of the first as a dynamic way of doing <script src=""/> and it might make sense to you why it is this way.

Stuart Branham
+9  A: 

Look at the code in the first script tag, it's writing another script tag to the page. The code in the second script tag is using a function that is in the file that is loaded by the written script tag, so it has to be in a separate tag as the file is not loaded until the first code has been executed.

You could put the scripts in separate files, but you still need to load them using two separate script tags as the first one has to be executed before the second one loads.

Guffa
I figured there was a technical reason for this as well.
Stuart Branham