Download Facebook Javascript SDK asynchronously

I am trying to download the all.js file asynchronously.

In my ASCX file:

<div id="fb-root"></div> 

I have a user control with javascript file included:

 window.fbAsyncInit = function () { FB.init({ appId: 'XXXXXXXXXXXXX', status: true, cookie: true, xfbml: true, oauth: true }); }; (function () { var e = document.createElement('script'); e.type = 'text/javascript'; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); } ()); 

However, when the page is displayed and loaded, the FB does not exist.

What gives?

+4
source share
2 answers

Sahil's answer is correct. By the time the document is submitted, there is no guarantee that asynchronous scripts are already loaded.

If your code from inside the fbAsyncInit not what you want, you can consider two alternative approaches:

Option 1

Download the sync SDK:

 <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script> 

Thus, the FB will exist even before the document starts rendering.

Option 2

Check if the SDK has already been loaded, and if you are not running a backup solution.

 if (window.FB) { // use FB here .. } else { // still loading, tell user to wait one more second } 
+2
source

This means that the FB is called before it is initialized. Since it is initialized by async, before you use FB for the first time, I suggest you write the FB.init code in your view, and not include it. Use like this:

 window.fbAsyncInit = function () { FB.init({ appId: 'XXXXXXXXXXXXX', status: true, cookie: true, xfbml: true, oauth: true }); // use FB here .. }; 
+1
source

All Articles