jnemecz
jnemecz

Reputation: 3608

Differences between two kinds of JS implementation in HTML

What are the differences between these two JavaScript implementations in an HTML file?

  1. <script src="foo.js" type="text/javascript"></script>

  2. As Google Analytics does it programatically:

      (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 
    'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
        })();
    

Are there any differences how the browser loads / renders the HTML page or is there some differences with the connection for caching such JS script?

Upvotes: 2

Views: 127

Answers (2)

karim79
karim79

Reputation: 342635

Your first script tag forces the browser to synchronously pull in that file; in other words, the browser will stop all other activity to download, parse and execute the script before proceeding with rendering the page.

In the second case (your google stuff), a script element is dynamically created and the file is loaded in asynchronously.

First tag is blocking, second one is not.

More on async:

More on the impact of "blocking" scripts:

Summary: put scripts at bottom of page if they're blocking.

Upvotes: 5

Quentin
Quentin

Reputation: 943547

In general, none.

In that specific case: Google are using a different host name to serve the SSL version from.

If you used the same hostname for the HTTP and HTTPS versions, you could just use:

<script src="//example.com/ga.js" async></script>

… for the same effect.

Note the addition of the async attribute, which was in the Google version (2) but not your (1).

Upvotes: 0

Related Questions