我正在开发一个IOS应用程序,但以下动态加载项目的代码似乎不起作用
var offset_c = 5;
$(window).scroll(function(){
var content = document.getElementById("wrap");
var content_height = content.offsetHeight;
var yoffset = window.pageYOffset;
var scrolloffset = yoffset + window.innerHeight;
if(scrolloffset >= content_height){
$.post("ajax/products_ajax.php?offset",{offset:offset_c},function(data){
$(".products").append(data);
offset_c = offset_c + 5;
});
}
});
上面的代码是做什么的,它发送ajax请求很好但是它反复加载接下来的10个产品(5-15)大约5次。没有真正解决代码的问题。
答案 0 :(得分:1)
您$.post()
代码会在滚动时触发。这意味着当用户在您的网站/应用程序中滚动(或滑动)时,它将被连续触发。这就是它反复触发5次或更多次的原因。你应该"去抖"滚动处理程序,以确保它不会继续调用。目前的代码也是对性能的巨大打击。在David Walsh blog上是一个很好的去抖代码:
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
在您的示例中,这看起来像这样:
var efficientScrollHandler = debounce(function() {
// All the taxing stuff you do
// Like $.post() and stuff
}, 250); // <-- gets triggered maximum one time per 250ms
$(window).scroll(efficientScrollHandler);