Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to include Javascript?

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?

like image 874
Paul Tarjan Avatar asked Jan 30 '11 07:01

Paul Tarjan


1 Answers

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/

like image 190
Joe Hanink Avatar answered Oct 13 '22 00:10

Joe Hanink