Search code examples
jqueryfacebookhtmlasynchronousfacebook-comments

Facebook Comments (html5) wont show if they are inserted on the DOM after loaded


I have a list of posts and a "load more" button to load more posts on an infinite scroll like twitter, etc.

The thing is that each post has Facebook Comments, but I don't want to load ALL the comments of EACH post.

So, I did this in jQuery:

function showFbComments(id) {
var commentBox = '<div class=\"fb-comments\" data-href=\"http://www.tusecreto.com.ar/' + id + '\" data-num-posts=\"20\" data-width=\"100%\"></div>';
if($('#fb_comentarios_' + id).hasClass("loaded")) {
    $('#fb_comentarios_' + id).toggle();
} else {
$('#fb_comentarios_' + id).addClass("loaded").append(commentBox).toggle();
}
}

This way, when I click on "50 Comments", the function showFbComments will show my "fb_comentarios_id" DIV and append the Facebook HTML5 code.

The problem is that the comments won't show after the page is loaded. If I click the link before the page is fully loaded the show just fine.

I think it has to be something about the JS of Facebook. I mean all that...

<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/es_ES/all.js#xfbml=1&appId=152950781809";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

Is there any way to load comments asynchronously?


Solution

  • I think I found the answer: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/

    I just added

    FB.XFBML.parse(document.getElementById('#fb_comentarios_' + id));
    

    after the append and it's working now. Is this correct?