8

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?

1 Answer 1

8

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.