Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
How To Lazy Load The Facebook Comments Plugin Using JavaScript
Oct 10, 2014Web DevelopmentComments (17)
The Facebook comments plugin is an easy-to-use comment system that you can put on nearly any webpage. It's main downside versus a self-hosted comment system is that it incurs a lot of http requests. This can cause your site to load slower and make it feel less responsive.

To avoid a less responsive site, you can lazy load the comments plugin. This makes it so that the plugin only loads when it comes into view.

Note: If you have another Facebook plugin elsewhere on the site, such as the Like button, you won't be able to lazy load the comments. This is because the Facebook API will have already been included, causing comments to load immediately.


Understand The Embed Code


The first thing you need to do is grab the official embed code from the Facebook developer site. It's important to understand how it works before proceeding, as you'll be modifying it. The embed code should look like this (HTML5):

<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/sdk.js#xfbml=1&appId=YOUR_APP_ID&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<div class="fb-comments" data-href="YOUR_WEBPAGE" data-numposts="5" data-colorscheme="light"></div>

Here's what each element does: The first div is a placeholder element that Facebook uses as part of its SDK. The second div is what contains the comments. It doesn't do anything until the Facebook API is loaded. The script loads the Facebook API after making sure it hasn't been already loaded.


HTML Elements


Place both div elements into your HTML where Facebook told you to, but do not put the script in. On the second div, add the attribute id="comments". Your HTML should contain something like this:

<div id="fb-root"></div>

<div id="comments" class="fb-comments" data-href="YOUR_WEBPAGE" data-numposts="5" data-colorscheme="light"></div>

Don't forget to change YOUR_WEBPAGE to the correct value.


JavaScript Modifications


Now create a JavaScript function that loads the Facebook API on command (and not immediately like the original embed code does). The code is much simpler, since it doesn't need to check if the API has already been loaded. Put this into your JavaScript somewhere:

function loadAPI() {
var js = document.createElement('script');
js.src = '//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=YOUR_APP_ID&version=v2.0';
document.body.appendChild(js);
}

Don't forget to change YOUR_APP_ID to the correct value.

You can now call this loadAPI function at any time and it will load the Facebook API, thus filling in the comments div with comments.


Load When In View


You could choose to fire the loadAPI function from a button click, but a more user-friendly approach is to have it load automatically once the comments come into view. To do this, have JavaScript monitor the scroll event and keep checking the position of the div relative to the window height:

window.onscroll = function () {
var rect = document.getElementById('comments').getBoundingClientRect();
if (rect.top < window.innerHeight) {
loadAPI();
window.onscroll = null;
}
}

I kept the code short at the expense of extensibility and performance. You may want to adjust it to suit your needs, or put into your event handler system.


Complete Code


Here is the code all together:

<script>
function loadAPI() {
var js = document.createElement('script');
js.src = '//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=YOUR_APP_ID&version=v2.0';
document.body.appendChild(js);
}

window.onscroll = function () {
var rect = document.getElementById('comments').getBoundingClientRect();
if (rect.top < window.innerHeight) {
loadAPI();
window.onscroll = null;
}
}
</script>

<div id="fb-root"></div>

<div id="comments" class="fb-comments" data-href="YOUR_WEBPAGE" data-numposts="5" data-colorscheme="light"></div>

As you can probably imagine, you can lazy load any external asset, including Google's API, other scripts, and images.
Comments (17)
Add a Comment
anton   Oct 22, 2020
whats about the nounce tags? i tried with different script and its work but in new facebook script it has aditional nonce="xxxxxx" parameter ...without it this script stopped working
hmm   Jan 22, 2020
What should I do to load two or more scripts in such way? Could you tell me what to do?
Bad   Dec 19, 2019
- Only 1 page comment box is displayed for all pages. No separate comments for each page. data-href="YOUR_WEBPAGE" ==> True data-href="<?php the_permalink(); ?>"
best   Nov 20, 2019
Good code !! you is boss
HYTTR   Nov 04, 2019
great
Power   Feb 02, 2019
Saved me a lot of time! thanks!!
yo   Dec 23, 2018
that's great
Leo   Nov 21, 2018
Hi Nick, This way working perfectly on desktop browser, but how can I make it work on mobile. Thanks
Juanma Fernandez   Dec 22, 2016
Great!! Thanks..
Amritha Baburaj   Nov 30, 2016
ok
rozimages   Feb 05, 2016
Thanks for this. Gained quite a few PageSpeed points after implementing it. And how about your share bar?
Nick Vogt   Jan 04, 2016
Thank you. To accomplish that you would probably want to put loadAPI inside of a setTimeout call. Something like: setTimeout(loadAPI, 3000);
Errol Williams   Jan 04, 2016
Excellent written instructions that are very easy to follow. Nick, I have a question. If I wanted to load the facebook comment plugin after a short delay (let's say 3 seconds) instead of when the user scrolls, what tweaks will I have to make to your code to accomplish this?
Nick Vogt   Dec 28, 2015
Yes, you probably do have to use a Facebook meta tag in order to moderate from the site. I don't remember specifically.
Cristhian Almora   Dec 27, 2015
I used your code and it works perfect! Thanks for sharing. But I thought you have to add "Moderation Tool" to your blog with the meta tag of Facebook in the head>? Do you add meta tag in de header?
Nick Vogt   Dec 27, 2015
Yes. It shows "Moderation Tool" right next to the comment count (after loading). I usually moderate comments from facebook.com though.
Cristhian Almora   Dec 27, 2015
Do you see the moderation tool of facebook at your comments? It does not work for me. Any advice?