Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference does it make to use several script blocks on a web page?

Edit: As Andrew Moore pointed out this question is a duplicate of Two separate script tags for Google Analytics? So this question should be deleted to avoid cluttering Stack Overflow, unless there is a point in keeping this one, since it will probably show up in slightly different searches.

What difference does it make to use more than one script block on a web page? I have pasted in the standard code for including Google Analytics as an example, and I have seen the same pattern used in other places. Why is this code separated into two separate script blocks instead of just using a single one?

<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-x");
        pageTracker._trackPageview();
    } catch(err) {}
</script>
like image 803
Jan Aagaard Avatar asked Jun 06 '10 21:06

Jan Aagaard


People also ask

Why is the order of script tags important?

Script tags are executed in the order they appear It also means scripts which appear later on the page can depend on things scripts which appear earlier have done. Elements on the page won't render until all the script tags preceding them have loaded and executed.

How many script tags are allowed in an HTML file?

The number of script tags loaded increases the more the user navigates through the application. Is there a limit imposed by HTML on how many script tags can appear in the head of a document? no, there's no real limits to html, but anything more than a few (say 10, max) script tags is getting into ludicrous territory.

What is the use of script tag in HTML?

The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.

Is script tag blocked?

SCRIPT tags have a negative impact on page performance because of their blocking behavior. While scripts are being downloaded and executed, most browsers won't download anything else.


1 Answers

The second <script> contains code that depends on google-analytics.com/ga.js loading.

Non-deferred scripts are executed in the order in which they exist in the DOM.

The first <script> injects a new <script> after itself (with the src pointing to google's ga.js) which immediately loads and executes -- only then does the second <script> get executed.

like image 145
James Avatar answered Nov 15 '22 14:11

James