我刚刚通过将以下标记添加到 html.erb 页面中,在我的 Rails 应用程序上放置了一个类似 facebook 的按钮:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId=1419...&xfbml=1"></script><fb:like href="" send="" width="100" show_faces="" font="" layout="button_count" action="recommend"></fb:like>
而且......工作正常,但当 facebook sdk 加载时,我在页面上看到一个很大的空白区域。因此,我想尝试将其放入 application.js 文件中,并在页面加载后运行该函数。唯一的问题是我根本无法让它工作:)
到目前为止,我已将“fb-root”div 保留在 html 中,并将以下函数放入 application.js
$(function() {
$('#fb-root').after('<script src="http://connect.facebook.net/en_US/all.js#appId=1419...&xfbml=1"></script><fb:like href="" send="" width="100" show_faces="" font="" layout="button_count" action="recommend"></fb:like>');
});
但是,这对我不起作用,我不明白为什么(我是一个 js 新手)。任何帮助将不胜感激。谢谢!
最佳答案
您应该加载 javascript 函数 asynchronously :
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
然后,一旦 javascript 库加载,它会将您的 fbml 之类按钮转换为适当的 html iframe 代码。如果它在加载之前显示空白,请将“like”按钮 fbml 代码放入 div 中,并使用 css 设计该 div 的样式。
这是一个完整的示例,没有您正在讨论的问题(我异步加载 JavaScript 库,通过定时延迟来模拟缓慢加载。请注意,加载按钮加载时没有白色。
<!DOCTYPE html>
<html>
<body bgcolor="#000">
<div id="fb-root"></div>
<fb:like href="http://stackoverflow.com" send="" width="100" layout="button_count" action="recommend"></fb:like>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true, xfbml: true});
};
(function() {
// delay to simulate slow loading of Facebook library - remove this setTimeout!!
var t = setTimeout(function() {
alert('loading fb');
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}, 3000);
}());
</script>
</body>
</html>
关于ruby-on-rails - 在 Rails 中使用不显眼的 js 制作 Facebook Like 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542123/