How to detect when facebook's FB.init is complete

后端 未结 12 2329
我寻月下人不归
我寻月下人不归 2020-11-28 01:28

The old JS SDK had a function called FB.ensureInit. The new SDK does not seem to have such function... how can I ensure that I do not make api calls until it is fully initia

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 02:11

    While some of the above solutions work, I thought I'd post our eventual solution - which defines a 'ready' method that will fire as soon as FB is initialized and ready to go. It has the advantage over other solutions that it's safe to call either before or after FB is ready.

    It can be used like so:

    f52.fb.ready(function() {
        // safe to use FB here
    });
    

    Here's the source file (note that it's defined within a 'f52.fb' namespace).

    if (typeof(f52) === 'undefined') { f52 = {}; }
    f52.fb = (function () {
    
        var fbAppId = f52.inputs.base.fbAppId,
            fbApiInit = false;
    
        var awaitingReady = [];
    
        var notifyQ = function() {
            var i = 0,
                l = awaitingReady.length;
            for(i = 0; i < l; i++) {
                awaitingReady[i]();
            }
        };
    
        var ready = function(cb) {
            if (fbApiInit) {
                cb();
            } else {
                awaitingReady.push(cb);
            }
        };
    
        window.fbAsyncInit = function() {
            FB.init({
                appId: fbAppId,
                xfbml: true,
                version: 'v2.0'
            });
    
            FB.getLoginStatus(function(response){
                fbApiInit = true;
                notifyQ();
            });
        };
    
        return {
            /**
             * Fires callback when FB is initialized and ready for api calls.
             */
            'ready': ready
        };
    
    })();
    

提交回复
热议问题