How to detect when the Facebook javascript function is ready?
I have been using this:
function FB_wait() {
if (typeof FB == 'undefined') {
window.setTimeout(FB_wait, 100);
} else {
more();
}
}
But there must be a better way
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);
}());
This is my init code..
According to the FaceBook JavaScript SDK Documentation you just need to create fbAsyncInit()
function. It'll be executed as soon as FB
will be ready:
var fbAsyncInit = function() {
// FB is ready
};
I did a window.fbReady() function, that behaves much like jQuery's ready function, in the way that will execute the function that you give it if the FB object is loaded, or will add it to a queue if not.
;(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));
You should insert any FB function inside the window.fbAsyncInit, but NOT in FB.init(), because it recive as paramether just an array of options. Your code should looks like:
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);
}());
};
精彩评论