通过无限滚动防止重复执行 [英] Preventing duplicate execution with infinite scrolling
问题描述
我正在尝试为类似Instagram的Rails应用程序实现无限滚动.但是,正在执行以渲染下一页要呈现的帖子的那段jQuery jode被执行了两次.
I am trying to implement infinite scrolling for my Instagram-like Rails app. However, the piece of jQuery jode that's being executed to render the next page of posts to be rendered is being executed twice.
我尝试添加一个hack,但这并不完全有效.
I tried adding a hack, but it's not entirely effective.
代码如下:
var exec = false;
$(window).scroll(function() {
if ($('#paginator').length) {
var url = $('#load_more').attr('href');
if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 50 && !exec) {
exec = true;
$.get(url, function(data) {
$('#paginator').append('<div class="spinner"></div>');
$.getScript(url);
}).done(function(){ exec = false; });
}
}
});
要重复的部分显然是重复的ajax请求,因此帖子块被追加了两次.
The part that's being repeated is obviously the duplicate ajax request so the posts chunk is being appended twice.
如何解决此问题?
推荐答案
首先,在某些浏览器中无法检查文档高度和窗口高度.因此,改为扩展jQuery,以通过一种名为inView
的新jQuery方法检查#load_more
或要触发分页的任何其他元素是否在视图中.其次,使用$.active
查看正在发生的活动ajax请求数量.如果为0,则可以触发无限滚动:
First of all, checking document height vs window height will not work in some browsers. So instead, extend jQuery to check if #load_more
or any other element you want to trigger the pagination is in view, via a new jQuery method called inView
. Second, use $.active
to see how many active ajax requests are happening. if it's 0 you can trigger the infinite scroll:
$.fn.inView = function(){
var rect = this[0].getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
$(window).scroll(function() {
if ($('#paginator').length) {
var url = $('#load_more').attr('href');
if (url && $('#load_more').inView() && $.active == 0) {
$.get(url, function(data) {
$('#paginator').append('<div class="spinner"></div>');
$.getScript(url);
});
}
}
});
这篇关于通过无限滚动防止重复执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!