Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a replacement for FB.ensureInit() now?

Tags:

facebook

I am loading FB API in asynchronous way:

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true,
             xfbml: true});
  };
  (function() {
    var e = document.createElement('script'); e.async = true;
    e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
</script>

How do I know when it is initialized? What is the replacement for FB.ensureInit() method that would prevent running enclosed code until API is initialized?

like image 377
serg Avatar asked Jun 04 '10 20:06

serg


People also ask

How do you keep up with events without Facebook?

First, log into the social network, then click Events on the left-hand side. Toward the bottom, there's an option to add events to your calendar of choice, like Microsoft Outlook, Google Calendar, or Apple Calendar.


1 Answers

When you load Facebook's script it will execute window.fbAsyncInit, that you already have in your script. If you include a method call as the last row, inside that method you can be sure FB has been initialized.

The code above becomes

window.fbAsyncInit = function() {
  FB.init({appId: 'your app id', status: true, cookie: true,
           xfbml: true});
  afterInit();
};

You can also define your own fbEnsureInit that works as previously and use a semaphore instead of a method call: (Originally from another answer.)

window.fbAsyncInit = function() {
  FB.init({appId: 'your app id', status: true, cookie: true,
           xfbml: true});
  fbApiInitialized = true;
};

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

Yet another way is described in Performance tips for Connect wiki. This approach inspects the state of the script and does a callback when the script is loaded.

So, in your code above, before appending the script insert the following code:

script.onload = script.onreadystatechange = function() {
  if ( !done && (!this.readyState || this.readyState == "loaded" ||
       this.readyState == "complete") ) {
    done = true;
    afterInit();
  }
};

The method afterInit will be called when the script is loaded.

like image 180
Jawa Avatar answered Nov 10 '22 18:11

Jawa