Loading Facebook Widgets with jQuery

March 3, 2016

If you ended on this article, you are probably aware that social widgets such as Facebook and Twitter will hurt your website's performance. Depending on the scope of your project, it can be solved with some jQuery magic.

I recently worked on a quick redesign of the BetterOptin website, which lead to some pagespeed optimizations. There a Facebook Like Box at the bottom of the page, which was slightly slowing down the site. Here's how I "fixed" it.

If your Facebook widget is located at the very bottom of the page, why on earth would you load the script when the page loads? When the user lands on your site or article, he might scroll all the way down. But you can be pretty sure that he's not going to interact with your social widgets. The user needs to go trough your content first, and then eventually decide to follow your Facebook page.

In my opinion, we should serve stuff to the user when they need it.

Delaying the load of the Facebook SDK

Thanks to jQuery, loading a script after xx seconds is pretty straight forward. Here you go:

jQuery(document).ready(function ($) {

	/**
	 * Load Facebook after 3 seconds using jQuery
	 * https://developers.facebook.com/docs/javascript/howto/jquery/v2.5
	 */
	var FacebookLikeBox = $('.fb-like-box');
	if (FacebookLikeBox.length) {
		setTimeout(
			function () {
				$.ajaxSetup({
					cache: true
				});
				$.getScript('//connect.facebook.net/en_US/sdk.js', function () {
					FB.init({
						appId: '647293568670589',
						version: 'v2.5'
					});
					FB.XFBML.parse();
				});
			}, 3000);
	}

});

Please leave some feedback in the comments.