Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to workaround 'FB is not defined'?

Sometimes I'm getting the "FB is not defined" issue when loading the http://connect.facebook.net/en_US/all.js

I've realized that the problem is because sometimes my website just doesn't load that file. So it gets nothing, and the object FB literally doesn't exist.

My solution is to prevent my users when this happens, so I've tried the following codes in JavaScript but none seems to work:

if (FB) {/*run the app*/} else {/*alert the user*/} if (FB!==false) {/*run the app*/} else {/*alert the user*/} if (FB!='undefined') {/*run the app*/} else {/*alert the user*/} 

thanks for the answer!

like image 985
Raul Leaño Martinet Avatar asked Mar 16 '11 20:03

Raul Leaño Martinet


2 Answers

I think you should solve the main issue instead, which solution is provided by Facebook (Loading the SDK Asynchronously):

You should insert it directly after the opening tag on each page you want to load it:

<script>   window.fbAsyncInit = function() {     FB.init({       appId      : 'your-app-id',       xfbml      : true,       version    : 'v2.1'     });   };    (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/sdk.js";      fjs.parentNode.insertBefore(js, fjs);    }(document, 'script', 'facebook-jssdk')); </script> 

From the documentation:

The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML that will asynchronously load the SDK into your pages. The async load means that it does not block loading other elements of your page.

UPDATE: using the latest code from the documentation.

like image 88
ifaour Avatar answered Sep 18 '22 15:09

ifaour


Assuming FB is a variable containing the Facebook object, I'd try something like this:

if (typeof(FB) != 'undefined'      && FB != null ) {     // run the app } else {     // alert the user } 

In order to test that something is undefined in plain old JavaScript, you should use the "typeof" operator. The sample you show where you just compare it to the string 'undefined' will evaluate to false unless your FB object really does contain the string 'undefined'!

As an aside, you may wish to use various tools like Firebug (in Firefox) to see if you can work out why the Facebook file is not loading.

like image 35
Rob Levine Avatar answered Sep 17 '22 15:09

Rob Levine