Reputation: 3608
What are the differences between these two JavaScript implementations in an HTML file?
<script src="foo.js" type="text/javascript"></script>
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
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
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