shashi
shashi

Reputation: 4696

Using Jquery with facebook JS SDk

I am using jquery to achieve a variety of stuff in my pages, which includes showing and hiding div elements.

Now I also have the facebook JS SDK in the master page to check whether the user has signed out of facebook and making graph api calls.

The problem is sometimes, it takes a while for response from facebook to come and in this while, div elements which are hidden by jquery on $.ready, can be seen by the user.

Any ideas how to better this?

Upvotes: 1

Views: 3995

Answers (4)

jcoffland
jcoffland

Reputation: 5431

If you want a cleaner method, try this:

window.fbAsyncInit = function() {
  FB.init({xfbml: true});
};

$(function() {
  $.getScript({url: document.location.protocol +
    '//connect.facebook.net/en_US/all.js'});
}

Insert this code either inline or in a separate Javascript file.

Notes:

  • This example does not define appID, cookie or status. You could add them to fbAsyncInit.
  • Tested with JQuery 1.8.2.
  • I found the #fb-root div to be unnecessary.

Upvotes: 1

shashi
shashi

Reputation: 4696

Ok.. So I was finally able to resolve the issue. You should load the FB Javascript SDK asynchronously as shown below

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({appId: 'your app id', status: true, cookie: true,
             xfbml: true});
  };
  (function() {
    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>

For more details, please refer http://developers.facebook.com/docs/reference/javascript/

A thing which I noticed, all your methods containing FB object such as FB.api etc. should be within the same closure as FB.init or the FB object is undefined.

Upvotes: 2

Peter Bailey
Peter Bailey

Reputation: 105868

Defer to window.load

Upvotes: 0

Alexandros B
Alexandros B

Reputation: 1891

i think the graph api calls have a callback function for when they complete. invoke your jquery code from there instead of $.ready

Upvotes: 0

Related Questions