Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Facebook Javascript SDK loaded asynchronously?

I am using the standard Facebook Javascript code in my Facebook app, which I got in my sample app on Heroku. I don't really understand it, but by being careful I've been able to modify the sample app to do some basic things that are useful for me.

My understanding is that this code somehow loads the Facebook Javascript SDK. That is, it loads a javascript code file. What file is it really loading? Why can't I just load it like I load any other javascript code file? For example:

<script type="text/javascript" src="/javascript/jquery-1.7.1.min.js"></script>

The downside of this highly complicated approach is that I can't make heads or tails of it, and because I don't understand it, I have no intuition about how to use it.

Code here:

<script type="text/javascript">
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '<?php echo AppInfo::appID(); ?>', // App ID
      channelUrl : '//<?php echo $_SERVER["HTTP_HOST"]; ?>/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true // parse XFBML
    });

    // Listen to the auth.login which will be called when the user logs in
    // using the Login button
    FB.Event.subscribe('auth.login', function(response) {
      // We want to reload the page now so PHP can read the cookie that the
      // Javascript SDK sat. But we don't want to use
      // window.location.reload() because if this is in a canvas there was a
      // post made to this page and a reload will trigger a message to the
      // user asking if they want to send data again.
      window.location = window.location;
    });

    FB.Canvas.setAutoGrow();
  };

  // Load the SDK Asynchronously
  (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";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>
like image 652
Matthew Haines Avatar asked Feb 22 '13 08:02

Matthew Haines


1 Answers

It makes your site load faster because it doesn't need to wait for a response from the facebook server.

The window.fbAsyncInit is a callback and executes when the script is loaded. So when the facebook server is down, this function never gets called.

When the api is loaded all functionality of the API is available. Just check the docs. http://developers.facebook.com/docs/reference/javascript/

Hope this clarifies.

like image 123
Tom Avatar answered Nov 16 '22 02:11

Tom