FB is undefined even though I just used it-Collection of common programming errors

I had this problem and solved it similarly to the solution that Amry provided so I’m posting it here in case someone else needs to use it.

I made the initial assumption that the FB initialization call made in the fbAsyncInit method would initialize immediately, so I too coded my use of the FB object in a $(document).ready() method. That is not the case. fbAsyncInit takes quite some time after the page loads to finish initializing. Here is my solution, when using jQuery on my site:



  window.fbAsyncInit = function() {

    FB.init({
      appId      : 'your_app_id', // App ID
      channelUrl : 'your channel',
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });
    jQuery(document).trigger('FBSDKLoaded'); //This is the most important line to solving the issue
  };

  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=269187653191150";
     ref.parentNode.insertBefore(js, ref);
   }(document));


The last task is to simply switch your $(document).ready() code to a bind for your event. This goes where ever you are using the FB object.

(function($) {
    $(document).bind('FBSDKLoaded', function() {
        //Code using the FB object goes here.
    });

})(jQuery);

One thing I should also mention: Firefox is a lot more tolerant of this than Webkit browsers like Chrome. I couldn’t figure out why NONE of my jQuery was working properly in Chrome… well, this was why.

I hope this helps someone.