Thomas Carlton
Thomas Carlton

Reputation: 5968

How to handle Facebook javascript SDK events?

I have a javascript code that should execute some functions using Facebook API.

According to the documentation I'm including the SDK as follows. This code is included in a template for all the pages of my web application. (A template in my case is something that is added to all the pages...)

window.fbAsyncInit = function() {
  FB.init({
    appId            : 'xxx',
    autoLogAppEvents : true,
    xfbml            : true,
    version          : 'v2.10'           
  });

  jQuery('.FacebookLoadingFlag').trigger('facebook:init');
  FB.AppEvents.logPageView();                        
};

Now, on every page whenever I need to call a Facebook function, I try to execute it once the SDK initialized as follows:

window.onload = function() {           
  $(".FacebookLoadingFlag").bind("facebook:init", function() {   
    // code here
  });
}

This implementation doesn't work well because sometimes the SDK got initialized and the whole page is not loaded yet, so the event facebook:init fires before it gets an event handler. Hence the code doesn't execute.

If I remove window.onload, I sometimes get the error saying that jQuery was not found. It means jQuery was not loaded yet.

In both cases very often the code doesn't execute.

Does anyone have an idea on when to execute this code and be sure it will always be executed? I'm new to Javascript and I don't know how to handle events.

Upvotes: 1

Views: 370

Answers (1)

ncardeli
ncardeli

Reputation: 3492

I think you should be following this tutorial, that's jQuery specific:

https://developers.facebook.com/docs/javascript/howto/jquery/v2.10

From the tutorial:

In this tutorial, you’ll learn how to incorporate the Facebook JavaScript SDK into your jQuery-based web app. Both jQuery and the JavaScript SDK provide their own solutions for deferring code execution until the libraries have loaded, and this tutorial will help you combine the two and ensure both are ready to use before you invoke the SDK.

The tutorial you are following instructions from is a generic one.

According to the jQuery specific guide I linked above, your code should look like this:

<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <title>jQuery Example</title>
  <script>
    $(document).ready(function() {
      $.ajaxSetup({ cache: true });
      $.getScript('//connect.facebook.net/en_US/sdk.js', function(){
        FB.init({
          appId: '{your-app-id}',
          version: 'v2.7' // or v2.1, v2.2, v2.3, ...
        });
        // After initialization code here
        $('#loginbutton,#feedbutton').removeAttr('disabled');
        FB.getLoginStatus(updateStatusCallback);
      });
    });
  </script>
</head>

Upvotes: 2

Related Questions