Lazy Loading Social Sharing Buttons

Social sharing buttons play a big part on the web today. They are used to drive traffic to the site, and if done correctly can be very successful. Unfortunately, the loading of these buttons has its downsides on performance. Having many social sharing buttons on your site can slow it down because it will block any other scripts from loading while it is waiting for the document to render the social media from the different domains.

In my last blog post, I wrote about asynchronously loading JavaScript. To achieve the best page load and responsiveness it is advisable to asynchronously load these social sharing buttons. However it isn't always that easy to do this without writing a lot of code to cope with the loads of different social buttons. This is where Socialite.js comes in. It's a great library that is very easy to implement and activate a load of social sharing buttons. I like that you can easily add Twitter, Google+, Facebook, LinkedIn and many more buttons with one library and no repeating code. For a demo of the code, please visit the demo site. I also really like the phrase that they use on the site - "If you're selling your soul, you may as well do it asynchronously".

There are some great samples on the site that run through an onload demo, hover demo, and scroll demo. In this post we are going to run through a scroll demo - this is pretty similar to lazy loading images and only loads the buttons when the user's viewport comes into place. In order to add it to your page, you will first need to add a reference to the script. Next, create an element with the class socialite and a class like twitter-share to specify the social network and type of widget.

In order to get it to simply load asynchronously, all you need to do is call it like so:

Socialite.load();

However, as we are going to run through the scroll demo we need to do things slightly differently. At the bottom of your page, include the following code.

The above code uses jQuery and listens for any changes to the window viewport. It then checks if the socialButtons element is within the viewport. I am pretty sure that you could write this more effectively, but as I am not a JavaScript developer - you will have to forgive me!

In order to view a working demo, please click the following link. There is now no excuse not to load these social sharing buttons asynchronously - no more PageSpeed loading scores being affected by these buttons!