简体   繁体   中英

Loading Facebook Javascript SDK Asynchronously

I'm attempting to load the all.js file asynchronously.

In my ASCX file:

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

I've got a user control with an include of a javascript file:

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 renders and loads, FB does not exist.

What gives?

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

If running your code from inside the fbAsyncInit callback is not what you want, you may consider two alternative approaches:

Option 1

Load the SDK synchronousy:

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

By doing so, FB will exist even before the document starts rendering.

Option 2

Check if the SDK has been already loaded and provide a fallback solution when not.

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

That means the FB is called before it is initialized. Since it is initialized async, before the first time you use FB I would suggest you to write the FB.init code in you view instead of including it. Use like this-

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

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