Faster Social Sharing Widgets Using AJAX &  jQuery

Faster AJAX Sharing Widgets with jQuery & AJAX Over the past year Facebook, Twitter, LinkedIn, Google+, and other social media websites have continued to gain popularity around the web. Providing users with simple and easy ways to share content is now, without a question, a web design standard. Adding widgets to your website is easy, but the scripts provided by most major social networks can cause a significant increase in page load speed.

Using the following jQuery/AJAX loading method you can significantly decrease the initial load time of your website. This method is currently being used on the OpenView Venture Partners blog, where we have seen a 500% improvement in page speed, reducing the time it takes for a new visitor to load a page by 12 seconds (15 seconds to 3 seconds) according to Pingdom Tools. Boston Innovation is also using a modified version of this script combined with the jQuery Sonar plugin for lazy loading created by ArtzStudio.

How it Works

The concept is simple; provide users with an image of the social sharing widgets on page load, and then load them using AJAX when they are needed. This example will load the widgets for a given post when a visitor hovers over a .post container. jQuery will remove the CSS background (share-widget-buttons.png) for the .lazy-share-widget DIV. Unique ID’s are used to match each set of sharing widgets with the correct post.

I’ve chosen to focus on social sharing widgets for 4 popular social media websites:

  1. Facebook Like
  2. LinkedIn Share
  3. Twitter Tweet
  4. Google Plus+

The methods used could be adapted to other social networks, but some configuration will most certainly be required.

HTML & CSS Structure

The HTML structure is based on a standard WordPress blog post, but it will work with whatever setup you need. WordPress is not a requirement, however, you will need to dynamically set your DIV id’s in order for this widget to load sharing widgets for the correct post.

In WordPress this is simple, just replace id="post-1
with id="post-" and, similarly, replace id="sharing-1
with id="sharing-".

<div class="post clearfix" id="post-1">
  <h2 class="post-title"><a href="/" rel="bookmark">Sample Blog Post Title</a></h2>

  <p class="author-meta">1 hour ago by <a href="/about/" title="About Kevin Leary, a Boston Web Designer" rel="author">Kevin Leary</a></p>

  <div class="entry-content clearfix">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate veli dolore eu fugiat nulla pariatur.</p>
  </div><!--// end .entry -->

  <a href="/" class="small-btn">Continue Reading</a>

  <div class="lazy-share-widget" id="sharing-1">
    <div class="platform facebook" id="fb-newshare-1"></div>
    <div class="platform linkedin" id="linkedin-newshare-1"></div>
    <div class="platform twitter" id="tweet-newshare-1"></div>
    <div class="platform gplus"><span id="gplus-newshare-1"></span></div>
  </div>
</div><!--// end #post-XX -->

The CSS required in the demo is very basic, additional styles are included in an ajax-sharing.css external style.css stylesheet.

.lazy-share-widget {
  font-size:11px;
  font-style:normal;
  font-weight:bold;
  min-width:211px;
  height:20px;
  margin-top:12px;
  background:#fff url(share-widget-buttons.png) 0 0 no-repeat;
  float:left;
}
.lazy-share-widget .platform {
  height:20px;
  float:left;
  display:inline;
}

AJAX & jQuery

The ajax-widgets.js file handles the AJAX loading of the sharing widgets. This jQuery script will interact with a few elements in the document:

  • #post-XX — The container element that triggers the process for a given post or article
  • .post-title a — The link that will be shared comes from the href attribute of this link
  • #sharing-XX — The CSS background image will be removed
  • #fb-newshare-XX — This DIV will be replaced with the Facebook Like button
  • #linkedin-newshare-XX — This DIV will be replaced with the LinkedIn Share button
  • #tweet-newshare-XX — This DIV will be replaced with the Tweet button
  • #gplus-newshare-XX — This DIV will be replaced with the Google Plus+ button

If you plan to restructure the HTML used in the example it’s important to understand that each of these elements is required in order for the script to work properly.

/**
 * AJAX Sharing Widgets
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * Code inspired by TechCrunch development team at 10up (https://www.get10up.com/)
 */
(function($){

  // Facebook JS Async
  (function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'https://connect.facebook.net/en_US/all.js?ver=MU#xfbml=1';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
  })();

  // Share Widgets
  $('div[id^="post"]').bind("mouseenter", function(){
    // Post details
    var id = $(this).attr("id").slice(5);
    var permalink = $('.post-title a', this).attr("href");
    var title = $('.post-title a', this).text();

    // Remove icon images
    $('#sharing-' + id).css('background', 'none');

    // Facebook
    var fb_str = '<fb:like href="' + permalink + '" layout="button_count" send="false" show_faces="false"></fb:like>';
    $('#fb-newshare-' + id).removeClass('facebook').css('width', 'auto').html(fb_str);
    FB.XFBML.parse(document.getElementById('fb-newshare-' + id));

    // LinkedIn
    var linkedin_str = '<scr' + 'ipt id="inshare-' + id + '" type="in/share" data-url="' + permalink + '" data-counter="right"></scr' + 'ipt>';
    $('#linkedin-newshare-' + id).css('width', '110px').removeClass('linkedin').html(linkedin_str);
    if (typeof(IN) != 'object') 
      jQuery.getScript('https://platform.linkedin.com/in.js');
    else 
      IN.parse(document.getElementById('linkedin-newshare-' + id));

    // Twitter
    var twitter_str = '<span style="float:left;width:100px;margin-right:5px;"><iframe allowtransparency="true" frameborder="0" scrolling="no" src="https://platform.twitter.com/widgets/tweet_button.html?url=' + permalink + '&amp;text=' + title + '&amp;via=techcrunch" style="width:130px; height:50px;" allowTransparency="true" frameborder="0"></iframe></span>';
    $('#tweet-newshare-' + id).css('width', '110px').removeClass('twitter').html(twitter_str);

    // Google Plus
    $('#gplus-newshare-' + id).parent().removeClass('gplus');
    if (typeof(gapi) != 'object') jQuery.getScript('https://apis.google.com/js/plusone.js', function () {
      gapi.plusone.render('gplus-newshare-' + id, {
        "href": permalink,
        "size": 'medium'
      });
    });
    else {
      gapi.plusone.render('gplus-newshare-' + id, {
        "href": permalink,
        "size": 'medium'
      });
    }

    // Only load this process once
    $(this).unbind('mouseenter mouseleave');
  });
})(jQuery);

In Conclusion

Website speed and perceived load time has a major effect on a user’s experience and Google is now using site speed to calculate search engine rankings. If you’re in charge of development for a high volume publication or website that uses more than 4 social sharing widgets on a given page then you should consider using a progressive AJAX approach to loading your social sharing widgets.

Useful Resources

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.