When working with the Facebook api, there likely comes a time when you will need to know that FB.init has finished successfully and you can run your scripts to create a wonderful user experience.
Looking into this, it turns out that parts of FB.init runs asynchronously even when using the sync version suggested in the API. This obviously means that you simply cannot trust that your script will work just because you called it after the init call.
To work around this until the Facebook people fix the issue or provide a reliable event or callback, many have suggested various solutions based on timers. A more solid approach can be built around the FB api itself:
Looking into this, it turns out that parts of FB.init runs asynchronously even when using the sync version suggested in the API. This obviously means that you simply cannot trust that your script will work just because you called it after the init call.
To work around this until the Facebook people fix the issue or provide a reliable event or callback, many have suggested various solutions based on timers. A more solid approach can be built around the FB api itself:
Loading FB API asynchronously:
<script type="text/javascript">
window.fbAsyncInit = function() {
/**
* Workaround for FB.init not being synchronous nor providing a callback method.
*/
FB.init({
appId : 'YOUR_APP_ID_HERE',
cookie : true,
status : true,
xfbml : true,
oauth : true
});
FB.getLoginStatus(function(oResponse) {
if (oResponse.status === 'connected') {
// the session is complete, and fully initiated,
// go ahead and call your scripts here
} else {
// There was a problem, probably because the user was not logged in,
// so put a login sequence or your error handling of choice here
}
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementsByTagName('head')[0].appendChild(e);
}());
</script>
Loading FB API synchronously:
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
/**
* Workaround for FB.init not being synchronous nor providing a callback method.
*/
FB.init({
appId : 'YOUR_APP_ID_HERE',
cookie : true,
status : true,
xfbml : true,
oauth : true
});
FB.getLoginStatus(function(oResponse) {
if (oResponse.status === 'connected') {
// the session is complete, and fully initiated,
// go ahead and call your scripts here
} else {
// There was a problem, probably because the user was not logged in,
// so put a login sequence or your error handling of choice here
}
});
</script>