Last Updated: February 25, 2016
·
1.127K
· alanho

Ensure presence of FB JSDK with jQuery $.Deferred object

When I develop Facebook App/Tab, I need to make Facebook JS api call quite often. But sometimes, I might be calling method on the FB object too early before FB is completely loaded. Instead of setting a timer to do all FB-related calls after certain time, which is quite unreliable, I make use of jQuery $.Deferred object to make this a lot easier. You can setup the FB init block this way, along with a $.Deferred object. And once the FB object is loaded, you resolve the deferred object so all scripts that depend on the deferred object will be triggered once FB is loaded. $.Deferred is pretty neat!

<script type="text/javascript">
(function(){
  var deferred = $.Deferred();
  window.fb_loaded = deferred.promise();

  window.fbAsyncInit = function() {
      FB.init({
        appId      : "",
        channelUrl : "/channel.html",
        status     : true,
        cookie     : true,
        xfbml      : true
      });

      deferred.resolve();
})();
</script>

Once you get this setup, in anywhere in the HTML with jQuery loaded, you can simply do something like this to make sure FB is loaded:

$.when(fb_loaded).then(function(){
    FB.Canvas.setAutoGrow();
});