你应该加载异步 JavaScript 库 http://developers.facebook.com/docs/reference/javascript/并将所有 FB 相关功能放入window.fbAsyncInit
方法:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
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.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
此代码异步加载 SDK,因此不会阻止加载
页面的其他元素。这对于确保
为用户和 SEO 机器人快速加载页面。
上面代码中的 URL 是与协议相关的。这让
浏览器通过与客户端相同的协议(HTTP 或 HTTPS)加载 SDK
包含页面,这将防止“不安全内容”警告。
函数分配给window.fbAsyncInit
一旦 SDK 运行
已加载。加载 SDK 后要运行的任何代码
应放置在该函数内并在调用之后FB.init
。
例如,这是您测试登录状态的地方 https://i.stack.imgur.com/O9FfD.jpg的
用户或订阅任何 Facebook 活动 http://github.com/facebook/php-sdk您的应用程序是
感兴趣的。
一个简单的例子如下:
<div id="fb-root"></div>
<script>
var isLoaded = false;
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
isLoaded = true;
// Additional initialization code here
};
function checkIfLoaded() {
if(isLoaded) console.log("LOADED!");
else console.log("NOT YET!");
return false;
}
// Load the SDK Asynchronously
(function(d){
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.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<a href="#" onclick="checkIfLoaded();">Check</a>
(Just clicked the check
link a couple of times)
请注意,您仍然可以在服务器端构建登录链接并WITHOUTJavaScript。使用示例PHP-SDK http://github.com/facebook/php-sdk:
$loginUrl = $facebook->getLoginUrl();
...
...
<a href="<?php echo $loginUrl; ?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>