开发者

Using Jquery with facebook JS SDk

开发者 https://www.devze.com 2023-01-15 20:47 出处:网络
I am using jquery to achieve a variety of stuff in my pages, which includes showing and hiding div elements.

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?


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.


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.


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


Defer to window.load

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号