Load Facebook Like Button Asynchronously

As some of you developers might know when you get the default Facebook Like code, the script loads the like button synchronously. When you add the synchronous Facebook Like button to your website, Page Speed Online will tell you to prefer asynchronous resources. If you are like me and want to get the best score possible in Page Speed you would want to know how to make it asynchronous.

Prefer asynchronous resources - Fetching resources asynchronously prevents those resources from blocking the page load. - Page Speed Insights
Prefer asynchronous resources message on Page Speed for Facebook Like Button

Here is the original code:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=###############";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Here is the modified code:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.async=true;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=###############";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

I figured this out by looking at the Google +1 code. It was as simple as adding one line of code. I can’t understand why Facebook didn’t implement this in its code. Same applies for Twitter Follow Button.

17 thoughts on “Load Facebook Like Button Asynchronously

  1. I used this and Pagespeed check shut up about aSync loading.
    Now if only i could get the same error resolved for twitter.
    Could you also figure that out please – it would make a lot of lives easier.

  2. Omer, you are the man! Plain and simple. Thanks. By the way, do you have the solution to the “Remove query strings from static resources” such as Facebook elements?

  3. This is great. No idea why this isn’t the default, or at least mentioned in the official code generator.

  4. not working on wp when I tested on google page speed insights speed before inserting the code 80 and after inserting the code it goes to 64 not works for me if there is any solution so please let me know

  5. Thank you very much for the tip, indeed a quick easy fix; can’t agree more with ppl wondering why fb devs chose not to have the script load in async mode by default.
    Both twitter & google scripts come with async as default.

Leave a Reply

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