What are the pros and cons of the 3 popular methods for including 3rd party js? Why do respected companies (jQuery, Google, Amazon) use different methods? In what situations does it make more sense to use each of these methods?
Option 1 (jQuery - src attribute):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Option 2 (GA - insertBefore):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-WHATEVS']);
(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);
})();
</script>
Option 3 (Amazon - doc.write):
<script type="text/javascript">
document.write(unescape('%3Cscript type="text/javascript" src="'+document.location.protocol+'//abc.cloudfront.net/pages/scripts/0000/xxx.js"%3E%3C%2Fscript%3E'))
</script>
Option 1 is synchronous inclusion. That javascript will be read, parsed and executed before any following javascript.
Option 2 is asynchronous inclusion. It is loaded asychronously and has no guaranteed timing vs. other scripts in the page. This has the advantage that the rest of the page does not wait for it to load or execute, but the disadvantage that anything trying to use it has to know when it has been successfully loaded. The specific example you show for option 2 is for Google Analytics which is self contained and not dependent upon anything else in the page so it makes perfect sense to be asynchronous and not make anything else on the page wait for it to load.
Option 3 is still synchronous (like option 1), but obfuscates the inclusion of the script a little bit which fools some filters that may be trying to filter a specific script. It also allows you to use your own javascript to decide what scripts to include or where to include them from, but to have them included synchronously. You can also use your own javascript to manipulate the protocol (http/https) or domain if there's any reason to do that based on the loading page.