我在我的几个页面上设置了这个无限滚动功能。它工作得非常好,但是加载更多项目的 Ajax 调用会进行多次数据库调用,并且每次都必须加载大量图像,并且通常需要几秒钟才能加载。根据我的连接情况,我将其计时在 3 到 7 秒之间。因此,当浏览器决定多次触发滚动事件时,它可能会变成真正的火车残骸。我怎样才能对它进行节流或去抖动,以使浏览器不会在几秒钟内多次运行 Ajax 调用并使一切停止?
$(document).ready()
{
//Infinite scroll
$(window).on('scroll', _.debounce( function(){
var height = $(window).height();
var scrollTop = $(window).scrollTop();
var dHeight = getDocHeight();
if( height + scrollTop >= dHeight - 100)
{
//Display items that were previously hidden
showAllItems();
if(!vloaded < START_NUM && !done){
//Load next set of items
$.ajax
({
type: "POST",
url: "/organizer/getMore",
data: { filter: vfilter, loaded: vloaded },
dataType: "html",
success: function( responseText, textStatus, XHR )
{
if(responseText.indexOf("// GRID ENTRY //") < 0){ //Out of items to load
done = true;
}
else{
//Display items that were previously hidden
showAllItems();
// select the element with the ID grid and insert the HTML
$( "#grid" ).append( responseText );
//alert("Loaded "+vloaded+" items");
}
}
});
// global variable
vloaded +=LOAD_NUM;
} // if
}
}
}, 500, true)); // on
} // ready
编辑:
我下载了下划线并添加了去抖动功能,但现在 Ajax 调用似乎根本没有运行。即使我没有将 immediate 设置为 true,它应该在我停止滚动后很快执行,但它根本不执行。