Ajax-loading FB "like" button only works the first time

321 views Asked by At

I have a site where one part of the page (the #main-inner block) is loaded via AJAX, in order to speed up navigation. This page fragment can contain various social buttons (twitter, G+, facebook) which are initialized after the AJAX call has completed successfully and the HTML has been injected to the page.

This AJAX loading can happen several times while the visitor is on the page: each time the #main-inner block is removed (via jQuery) and recreated when the AJAX call is successful.

My problem is that the facebook "like" button only initializes correctly after the first AJAX call. On the following calls, the facebook button doesn't appear any more, and after a while, the console shows this error message: fb:like failed to resize in 45s.

The other social buttons work fine.

Here's the function I use to initialize the facebook button after the content of the #main-inner block has changed:

var loadFacebook = function () {
    if ($('.fb-like').length){
        var options = {
            status: true,
            cookie: true,
            xfbml: true,
            appId: XXXXXXXXX
        };
        if (typeof (FB) != 'undefined') {
            // FB.init(options);
            FB.XFBML.parse(document.getElementById('main-inner'));
        } else {
            $.getScript('//connect.facebook.net/fr_FR/all.js', function () {
                FB.init(options);
            });
        }
    }
};

Why does it only work the first time?... Is there a way to reset, or unload the previous button before re-initializing the new one?

1

There are 1 answers

0
s427 On

I've managed to reset (and reload) the facebook button by emptying the FV variable each time it is re-initialized. So the function is now:

var loadFacebook = function () {
    if ($('.fb-like').length){
        var options = {
            status: true,
            cookie: true,
            xfbml: true,
            version: 'v2.3',
            appId: XXXXXXXXX
        };
        FB = null; // <- that's the key
        $.getScript('//connect.facebook.net/fr_FR/all.js', function () {
            FB.init(options);
        });
    }
};

I'm still curious to know if there's a better (cleaner?) way to do that.

However I'm not sure that's enough, because although the like button now correctly appears after each AJAX load, it appears that it's unable to read the newly ajax-injected data in the page, and therefore all the fields in the popup (that opens when clicking on the button) are empty... :-(