Many of the big players recommend slightly different techniques. Mostly on the placement of the new <script>
.
Google Anayltics:
(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);
})();
Facebook:
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());:
Disqus:
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
(post others and I'll add them)
Is there any rhyme or reason for these choices or does it not matter at all?
These are all effectively the same approach in spirit. The idea is to defer scripts so they don't block each other or document complete.
It's common practice to load extra outside resources after your site's content. When doing so, you want to both a) prevent blocking the onload event so your page is "finished" faster, and b) load resources in parallel, which the above do.
Steve Souders claims that "progressive enhancement" is the most important concept for site performance today. This concept suggests that you deliver your base page as fast as possible and then deliver extra content/services as needed, either on the load event or when the user asks for it.
There are frameworks nowadays that help. See http://headjs.com/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With