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?
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.