What is a replacement for FB.ensureInit() now?
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() {开发者_JAVA百科
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° 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();
};
2° 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(); }
}
}
3° 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.
精彩评论