I finally decided to join app.net today (hey, better late than never). To verify my domain, sitekickr.com, I was asked to place the "Follow @sitekickr on App.net" button on the home page.

Visually, I have no concerns, the home page itself doesn't receive much traffic compared to the rest of the site, and the button really doesn't look that bad. But, being a web developer, my other big concern was performance. Another hosted button means another script needs to be loaded.

I can use all the tricks, put the script right before the closing body tag, load it asynchronously, yada, yada, but it's still going to be loaded on all of my site's pages, regardless of whether the button is actually used on a given page.

There's the obvious server-side solution, conditionally outputting the JavaScript only on the pages that need it, i.e.

<?php if ($_SERVER['SCRIPT_NAME'] === '/index.php') { ?>
    
  <script type="text/javascript">
    // do the asynchronous load thing here
  </script>

<?php } ?>

And that type of thing will work great, if I only expect the button to be used on one page. Once you start using hosted social network buttons in various creative ways and all kinds of different sections and page, it'll will become difficult to manage the conditional used to output the JavaScript.

Then it hit me, why don't I let JavaScript decide when it should load the script! Afterall, JavaScript has direct access to the DOM and knows when I have an HTML element on page that requires a specific script to populate it.

In the example below, the app.net button has a class name of adn-button:

<a href='https://alpha.app.net/sitekickr' class='adn-button' 
   target='_blank' data-type='follow' data-width='277' 
   data-height='27' data-user-id='@sitekickr' 
   data-show-username='1' rel='me'>Follow me on App.net</a>

So, I can place the following in my main JavaScript file, which will only load the app.net button script when an element exists on the page the requires it:

if ($('.adn-button').length) {

  // load app.net button script

  (function(d,s,id){
    var js,fjs=d.getElementsByTagName(s)[0];
    if(!d.getElementById(id)){
      js=d.createElement(s);
      js.id=id;
      js.src='//d2zh9g63fcvyrq.cloudfront.net/adn.js';
      fjs.parentNode.insertBefore(js,fjs);
    }
  }(document, 'script', 'adn-button-js'));

}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *