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.

Example / Demonstration

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-".

Sample Blog Post Title

1 hour ago by

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.

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.

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.

Continue Reading

The CSS required in the demo is very basic, additional styles are included in an 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 http://mozilla.org/MPL/2.0/.
 *
 * Code inspired by TechCrunch development team at 10up (http://www.get10up.com/)
 */
(function($){

	// Facebook JS Async
	(function() {
		var s = document.createElement('script');
		s.type = 'text/javascript';
		s.async = true;
		s.src = 'http://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-newshare-' + id).removeClass('facebook').css('width', 'auto').html(fb_str);
		FB.XFBML.parse(document.getElementById('fb-newshare-' + id));
		
		// LinkedIn
		var linkedin_str = '';
		$('#linkedin-newshare-' + id).css('width', '110px').removeClass('linkedin').html(linkedin_str);
		if (typeof(IN) != 'object') 
			jQuery.getScript('http://platform.linkedin.com/in.js');
		else 
			IN.parse(document.getElementById('linkedin-newshare-' + id));
		
		// Twitter
		var twitter_str = '';
		$('#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('http://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