12

I am attempting to add like buttons to a page using the standard like button code as proided in the fb documentation:

https://developers.facebook.com/docs/plugins/like-button/

This is causing extremely slow loading due to the number of buttons I would like to add.

To get round this I was hoping to load the buttons as needed using jquery, but if I add the button code this way, they are appended to the the correct location (visible in the developer tools elements window) but the buttons do not appear.

Is there anyway to add these buttons dynamically? I am guessing it is not working because the buttons can't be added after initiation but I have no idea how to get around this.

I included the required code inside the body tag

<div id="fb-root"></div>
<script type="text/javascript">
    (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_GB/all.js#xfbml=1&appId=************";
        fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
 </script>

The fb-like code I am using is the one generated by the documentation:

<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="recommend" data-show-faces="false" data-share="true"></div>

I have tried adding a button this way:

   $(".myitem").append('<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button_count" data-action="recommend" data-show-faces="false" data-share="true"></div>');                   

UPDATE:

I have tried firing FB.XFBML.parse(); after appending the new buttons, but this refreshes all of the buttons on the page not just the newly appended ones.

1 Answer 1

28

To force the refresh / rendering of the Like button, you can use FB.XFBML.parse(); which go through the whole DOM document.

If you only want to go through a part of the document, you can pass a DOM object (which is for example a container element with 1 button).

FB.XFBML.parse(document.getElementById('containerX'));
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you don't pass the fb-like div to FB.XFBML.parse(), as @Mike says, you pass its parent!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.