2010-08-22 39 views
4

我一直用这个:如何检测Facebook javascript功能何时准备好?

function FB_wait() { 
    if (typeof FB == 'undefined') { 
     window.setTimeout(FB_wait, 100); 
    } else { 
     more(); 
    } 
} 

但是,必须有一个更好的办法

window.fbAsyncInit = function() { 
    FB.init({ 
     appId : '<?php echo $conf['fb']['appid']; ?>', 
     status : true, // check login status 
     cookie : true, // enable cookies to allow the server to access the session 
     xfbml : true // parse XFBML 
    }); 
    FB.Canvas.setAutoResize(); 
    }; 

    (function() { 
    var e = document.createElement('script'); 
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
    e.async = true; 
    document.getElementById('fb-root').appendChild(e); 
    }()); 

这是我的初始化代码..

+1

您是否异步加载FB的脚本? – Anurag 2010-08-22 23:44:59

+0

是的..我已经包含代码:) – Pablo 2010-08-23 14:10:07

回答

1

按照FaceBook JavaScript SDK Documentation你只需要创建fbAsyncInit()功能。它会尽快执行为FB将准备:

var fbAsyncInit = function() { 
    // FB is ready 
}; 
+4

这并不意味着FB启动。所有这一切都意味着FB功能的存在。如果您看到我编辑中包含的启动代码,您可以看到您提供的代码实际上是其中的一部分。 – Pablo 2010-08-23 14:12:03

0

我做了window.fbReady()函数,其行为很像jQuery的ready功能,将执行你给它的函数的方式如果FB对象被加载,或者如果不是,则将其添加到队列中。

;(function(){ 
    // Function to have a list of functions to load on fbAsyncInit 
    var toLoad = [] 
    window.fbReady = function(func){ 
    if(typeof func === 'function') { 
     if(window.FB) { 
     func.call(window) 
     } else { 
     toLoad.push(func) 
     } 
    } 
    } 

    window.fbAsyncInit = function() { 
    FB.init({ 
     appId: FACEBOOK_API_KEY, 
     status: true, 
     cookie: true, 
     xfbml: true 
    }) 

    // Execute all the fbAsyncInit functions 
    toLoad.forEach(function(func){ 
     func.call(window) 
    }) 
    }; 
})(); 
(function(d, debug){ 
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; 
    if (d.getElementById(id)) {return;} 
    js = d.createElement('script'); js.id = id; js.async = true; 
    js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js"; 
    ref.parentNode.insertBefore(js, ref); 
}(document, /*debug*/ false)); 
0

你应该插入window.fbAsyncInit内的任何FB的功能,但不是在FB.init(),因为它recive作为paramether只是一组选项。 您的代码应该如下所示:

window.fbAsyncInit = function() { 
    FB.init({ 
     appId : '<?php echo $conf['fb']['appid']; ?>', 
     status : true, // check login status 
     cookie : true, // enable cookies to allow the server to access the session 
     xfbml : true // parse XFBML 
    }); 

    // at this level, the FB library is ready 
    FB.Canvas.setAutoResize(); 
    FB.getLoginStatus(function(resp){ console.log(resp) }); 
    FB.any_fb_function(); 

    (function() { 
     var e = document.createElement('script'); 
     e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
     e.async = true; 
     document.getElementById('fb-root').appendChild(e); 
    }()); 
};