Wednesday, December 7, 2011

Facebook JavaScript SDK Call after FB.init()

When developing Facebook Apps, the JavaScript SDK is usually loaded asynchronously to not block loading other elements of your page. However, it leaves us a problem: every JavaScript SDK call must be made after the SDK loading. Otherwise, a "FB not defined" error will be thrown. There are two common ways to handle this situation.

Put the codes inside the callback function of fbAsyncInit process
<div id="fb-root">
  window.fbAsyncInit = function() {
      appId      : 'YOUR_APP_ID',
      channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html',
      status     : true,
      cookie     : true,
      oauth      : true,
      xfbml      : true
    // Put Your Codes Here

     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); = id; js.async = true;
     js.src = "//";

Add delay to your SDK call
 * do something when user leaves a new comment
function fb_event_subscribe() {
    try {
        FB.Event.subscribe('comment.create', function(response) {
            // do something here
    catch(err) {
        setTimeout("fb_event_subscribe()",1000); // try again later

 * subscribe the Facebook event "comment.create" after a one second delay, which
 * makes sure FB JavaScript SDK asynchronous initialization FB.init() is finished.

1 comment:

  1. The code you have provided has been really helpful in my work. It made the process easy and simple to access. Thanks for sharing this informative and helpful post.