user6589814 user6589814 - 2 months ago 84
Javascript Question

Load Facebook comment after click on show comments

I use Facebook comments plugin in my application. When page is visited, it slows down page load by some.

How can I add a button called Show comments and only after click on button

render
Facebook comments plugin.

Here is a example

This is what I have so far

<div class="fb-comments" data-href="https://developers.facebook.com/docs/plugins/comments#configurator" data-numposts="5"></div>

<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&version=v2.7&appId=<APP_ID>";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));


</script>

Answer

You can use a custom function

<button onClick="showComments();">show comments</button>


<div class="fb-comments" data-href="https://developers.facebook.com/docs/plugins/comments#configurator" data-numposts="5"></div>

<div id="fb-root"></div>
<script>
  function showComments() { // Custom function called on click
    (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&version=v2.7&appId=<APP_ID>";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  }

</script>