Tuesday, March 20, 2012

Loading Facebook social plugins in dynamic, ajax content

If you include a Facebook social plugin inside of a piece of content (JQuery UI dialog, template, whatever) that you add to the page dynamically, the plugin fails to render. This is because Facebook parses the page only initial load and so doesn't pick up the dynamic content. You need to explicitly tell it to re-parse the entire page, or just the new content.

So here I have a function that will use JQuery to load a piece of content containing Facebook plugins. All I need to do is call FB.XFBLM.parse(...) after the content is loaded and problem solved.



   
    var url = "/shared/facebooklikes";
    $(#facebookLikesPlaceholder").load(url, function () {
        FB.XFBML.parse(document.getElementById('facebookLikesPlaceholder'));
    });
   


Here's the article reference.

Now, there is a further complication if you are loading the Facebook SDK async. In this case, the script may not have been fully loaded by the time your ajax call is made and returns. So, you need to check that the script is loaded before you make your call to parse.

Here is a Stackoverflow post that addresses this case and which I'm using here.

Now, in the script block where I load the FB SDK, I add:


var fbApiInitialized = false;

FB.Init({}),fbApiInitialized = true;

(fbEnsureInit = function (callback) {
        if (!window.fbApiInitialized) {
            setTimeout(function () { fbEnsureInit(callback); }, 50);
        } else {
            if (callback) {
                callback();
            }
        }
    })();


So it looks like this:




And my ajax load method now looks like:


   
    var url = "/shared/facebooklikes";
    $(#facebookLikesPlaceholder").load(url, function () {
        window.fbEnsureInit(function () {
                FB.XFBML.parse(document.getElementById('facebookLikesPlaceholder'));
            });
    });
   


And it correctly checks that the script is loaded before calling FB.XFBML.parse().

2 comments: