What is the best way to include Javascript?

Posted by Paul Tarjan on Stack Overflow See other posts from Stack Overflow or by Paul Tarjan
Published on 2011-01-30T07:04:19Z Indexed on 2011/01/30 7:25 UTC
Read the original article Hit count: 201

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html