简体   繁体   中英

When to load Facebook Javascript SDK with multiple Like buttons and Timeline app?

I'm wondering how I should be loading the Javascript SDK if I have a Like button and a button that calls FB.login for a Timeline app on the same page. The code for the Like button uses the following:

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=126380467442965";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

but for the OAuth dialog for the app, Facebook suggests using:

<script src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root"></div>
<script>
  // assume we are already logged in
  FB.init({appId: '123050457758183', xfbml: true, cookie: true, oauth: true});
  ...
</script>

Which one should I use?

The different codes are async and synchronous implementations of the SDK. The first is async - the code will load up without affecting other elements on the page. The second (just including the script tag) is synchronous. The Facebook script will be loaded up, and it'll hold the page up while it loads.

The async implementation is often better - it should make the page feel faster. However, since the Facebook code is loaded after the page, we can't use any FB functions until we're sure it's loaded. So, the async implementation provides us with a callback, which fires when the SDK has loaded.

I think it'd be best to use the code from the first snippet, but add this code to initialise the SDK using the callback.

The FB.login on your button should work, alongside your like button.

window.fbAsyncInit = function() {
    FB.init({
        appId: ...,
        status: true,
        cookie: true,
                xfbml: true,
        oauth: true
    });

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM