感谢 Thomas 的回答,我创建了一个 FacebookApiLoader 类来执行此操作。这是源代码,目前仅在 Firefox 3 中测试。希望这可以帮助某人。这样做是查看页面上是否有任何 facebook api 依赖元素,如果有,它将通过在 body 结束标记之前插入 facebook api 脚本来加载它。这依赖于 PrototypeJS 库。在可能需要 facebook api 的页面中调用 facebookApiLoader.observe()。
var FacebookApiLoader = Class.create({
initialize: function() {
this.observer = null
this.observedElement = null
},
apiDependentsVisible: function() {
if (null == this.observedElement) {
// $('facebook-login') is a div in my site that
// is display:none initially. Once it is made
// visible then the facebook api is needed.
// Replace 'facebook-login' with id relevant for your site
this.observedElement = $('facebook-login')
}
return this.observedElement.visible()
},
apiLoadCompleted: function() {
try {
return !Object.isUndefined(FB) && !Object.isUndefined(FB_RequireFeatures)
} catch (e) {
}
return false
},
initAndRequireFeatures: function() {
FB_RequireFeatures(["XFBML"],
function() {
FB.init('secret-put-your-app-value-here','/xd_receiver.html', {})
}
);
},
initFacebookConnect: function() {
new PeriodicalExecuter(function(pe) {
if (this.apiLoadCompleted()) {
this.initAndRequireFeatures()
pe.stop()
}
}.bind(this), 0.2);
},
loadApi: function() {
// Use body for facebook script as recommended in Facebook
// docs not to insert in head as some browsers have
// trouble with it
body = $$('body')[0]
// TODO use https protocol if page is secure
script = new Element('script', { 'type': 'text/javascript',
'src': 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php' })
body.appendChild(script)
this.initFacebookConnect()
},
loadApiIfRequired: function() {
if (this.apiDependentsVisible()) {
this.observer.stop()
this.loadApi()
}
},
observe: function() {
if (null == this.observer) {
this.observer = new PeriodicalExecuter(this.loadApiIfRequired.bind(this), 0.2)
}
}
});
// The FacebookApiLoader attributes are lazily loaded
// so creating a new facebookApiLoader
// is as low resource usage as possible
var facebookApiLoader = new FacebookApiLoader();
然后在任何可能需要 Facebook api 的页面上,调用
facebookApiLoader.observe();