我知道这是一个老话题,但这可能会派上用场,对于其他人也有同样的问题。
如果您在搜索结果页面上有每吨结果的facebook小部件,并希望它们全都呈现,但不想在同一时间用大量连接击中用户,则可以使用它节制渲染。
代码:
var fbThrottle = (function() {
var settings = {
// how many widgets can be rendering at any one time
simultaneousRenders: 3,
// how often to add a new widget to the queue, if the queue is not full
renderInterval: 100,
// max amount of time we will wait until marking a widget as rendered
// this is in place so as not to block the queue if a widget takes too long
maxRenderWaitFailsafe: 5000,
// how long to wait before calling the callback function (if supplied)
// after a widget finishes rendering. can be used to say set the area visible after render if you had it hidden to prevent fout.
callbackDelay: 250,
};
var fbWidgets = [];
var activeRenders = 0;
setInterval(function() {
if (fbWidgets.length == 0)
return;
if (!window.FB)
return;
if (activeRenders < settings.simultaneousRenders) {
var obj = fbWidgets.shift();
if (typeof obj !== 'undefined') {
activeRenders++;
(function() {
var currentRenderDone = false;
setTimeout(function() {
if (!currentRenderDone) {
activeRenders--;
currentRenderDone = true;
}
}, settings.maxRenderWaitFailsafe);
window.FB.XFBML.parse(obj.widget, function() {
if (!currentRenderDone) {
activeRenders--;
currentRenderDone = true;
}
if (typeof obj.callback === 'function') {
setTimeout(function() {
obj.callback();
}, settings.callbackDelay);
}
});
})();
}
}
}, settings.renderInterval);
return {
add: function (widget, callback, top) {
if (typeof widget === 'undefined')
return;
if (typeof widget === 'string')
widget = document.getElementById(widget);
var obj = {
widget: widget,
callback: callback
};
if (top)
fbWidgets.unshift(obj);
else {
fbWidgets.push(obj);
}
},
};
})();
用法:
您可以将元素添加到油门一下子,或有声纳通过他们,因为他们变得可见。
// add in the element to be rendered to the end of the list
fbThrottle.add(element);
// or you can pass in just the id
fbThrottle.add("idOfElement");
// you can pass in a callback as well
fbThrottle.add(element, function(){
// do something after
});
// you can add an element to the top of the list by setting the third parameter to true
fbThrottle.add(element, callback, true);
由于Jakobud提到最好是在你的FB.init
window.FB.init({
xfbml: false
});
转向XFBML关闭如果是相同的URL,关闭FB JS API的小部件的自动渲染,什么是错的只有有一个按钮? – Bojangles 2012-02-03 22:16:39
它是页面设计的一部分。我只是开发人员,而不是设计师。 – 2012-02-03 22:19:09
我只是好奇;从外部的角度来看,似乎很难复制同一条信息30次,但当然它超出了你的控制范围:-) – Bojangles 2012-02-03 23:28:22