Skip to main content

How to detect when facebook"s FB.init is complete



The old JS SDK had a function called FB.ensureInit. The new SDK does not seem to have such function... how can I ensure that I do not make api calls until it is fully initiated?





I include this in the top of every page:







<div id="fb-root"></div>

<script>

window.fbAsyncInit = function() {

FB.init({

appId : '<?php echo $conf['fb']['appid']; ?>',

status : true, // check login status

cookie : true, // enable cookies to allow the server to access the session

xfbml : true // parse XFBML

});

FB.Canvas.setAutoResize();

};



(function() {

var e = document.createElement('script');

e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';

e.async = true;

document.getElementById('fb-root').appendChild(e);

}());

</script>





Source: Tips4all

Comments

  1. Update on Jan 04, 2012

    Seems like you can't just call FB-dependent methods (for example FB.getAuthResponse()) right after FB.init() like before, as FB.init() seems to be not synchronous now. Wrapping your code into FB.getLoginStatus() response seems to do the trick of detecting when API is fully ready:

    window.fbAsyncInit = function() {
    FB.init({
    //...
    });

    FB.getLoginStatus(function(response){
    runFbInitCriticalCode();
    });

    };


    or if using fbEnsureInit() implementation from below:

    window.fbAsyncInit = function() {
    FB.init({
    //...
    });

    FB.getLoginStatus(function(response){
    fbApiInit = true;
    });

    };




    Original Post:

    If you want to just run some script when FB is initialized you can put some callback function inside fbAsyncInit:

    window.fbAsyncInit = function() {
    FB.init({
    appId : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml : true // parse XFBML
    });
    FB.Canvas.setAutoResize();

    runFbInitCriticalCode(); //function that contains FB init critical code
    };


    If you want exact replacement of FB.ensureInit then you would have to write something on your own as there is no official replacement (big mistake imo). Here is what I use:

    window.fbAsyncInit = function() {
    FB.init({
    appId : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml : true // parse XFBML
    });
    FB.Canvas.setAutoResize();

    fbApiInit = true; //init flag
    };

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


    Usage:

    fbEnsureInit(function() {
    console.log("this will be run once FB is initialized");
    });

    ReplyDelete
  2. I've avoided using setTimeout by using a global function:

    window.fbAsyncInit = function() {
    FB.init({
    //...
    });
    window.fbApiInit = true; //init flag
    if(window.thisFunctionIsCalledAfterFbInit)
    window.thisFunctionIsCalledAfterFbInit();
    };


    fbEnsureInit will call it's callback after FB.init

    function fbEnsureInit(callback){
    if(!window.fbApiInit) {
    window.thisFunctionIsCalledAfterFbInit = callback; //find this in index.html
    }
    else{
    callback();
    }
    }


    fbEnsureInitAndLoginStatus will call it's callback after FB.init and after FB.getLoginStatus

    function fbEnsureInitAndLoginStatus(callback){
    runAfterFbInit(function(){
    FB.getLoginStatus(function(response){
    if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token
    // and signed request each expire
    callback();

    } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook,
    // but has not authenticated your app

    } else {
    // the user isn't logged in to Facebook.

    }
    });
    });
    }


    fbEnsureInit example usage:

    (FB.login needs to be run after FB has been initialized)

    fbEnsureInit(function(){
    FB.login(
    //..enter code here
    );
    });


    fbEnsureInitAndLogin example usage:

    (FB.api needs to be run after FB.init and FB user must be logged in.)

    fbEnsureInitAndLoginStatus(function(){
    FB.api(
    //..enter code here
    );
    });

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.