Facebook Javascript Ensure FB was initialized

Here’s a tip on how to make sure FB is initialized.

It is useful when you want to execute a FB call but are not sure if FB.init has already finished.

<body>
<div id="fb-root"></div>
<script>
function fbEnsureInit(callback) {
        if(!window.fbApiInit) {
            setTimeout(function() {fbEnsureInit(callback);}, 50);
        } else {
            if(callback) {
                callback();
            }
        }
    }
window.fbAsyncInit = function() {
    FB.init({
        appId  : '123456789',
        status : true, // check login status
        cookie : true, // enable cookies to allow the server to access the session
        xfbml  : true,  // parse XFBML
        oauth : true, //enables OAuth 2.0
    });

    // etc etc

    fbApiInit = true;
}; 

(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/pt_BR/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
</script>

<!--- etc etc --->

<script>
$(function() {
    var answer = confirm('Share ur review on fb?');

    if (answer)
    {
        fbEnsureInit(function() {
            FB.ui({
                    method: 'feed',
                    source: 'http://www.rovio.com/img/angrybirds_big.jpg',
                    name: 'Test',
                    caption: 'My cap',
                    description: 'My desc',
                    link: 'http://it.blog.adclick.pt'
                })
        });
    }
});

</script>

source

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>