Tutorial Async Sharing Buttons (G+, Facebook, Twitter)

by in , 0

Some of these services already (smartly) provide their scripts in an async fashion, this just combines them into more efficient, organized, and understandable code.

(function(doc, script) {
  var js, 
      fjs = doc.getElementsByTagName(script)[0],
      frag = doc.createDocumentFragment(),
      add = function(url, id) {
          if (doc.getElementById(id)) {return;}
          js = doc.createElement(script);
          js.src = url;
          id && (js.id = id);
          frag.appendChild( js );
      };
      
    // Google+ button
    add('http://apis.google.com/js/plusone.js');
    // Facebook SDK
    add('//connect.facebook.net/en_US/all.js#xfbml=1&appId=200103733347528', 'facebook-jssdk');
    // Twitter SDK
    add('//platform.twitter.com/widgets.js');

    fjs.parentNode.insertBefore(frag, fjs);
}(document, 'script'));

I found it going through some site code and I forget exactly who originally did it but it seems like a Nicolas Gallagher or Mathias Bynes kind of thing. Correct me if I'm wrong.

You'll need the HTML in place for the scripts to put their stuff:

<a href="https://twitter.com/share" class="twitter-share-button" data-count="horizontal">Tweet</a>

<div class="g-plusone" data-size="medium" data-count="true"></div>

<div id="fb-root"></div>
<div class="fb-like" data-send="false" data-layout="button_count" data-width="1" data-show-faces="false" data-action="recommend"></div>

Leave a Reply