Reputation: 9532
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.
I tried adding a hack, but it's not entirely effective.
Here's the code:
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; });
}
}
});
The part that's being repeated is obviously the duplicate ajax request so the posts chunk is being appended twice.
How can I fix this issue?
Upvotes: 1
Views: 1072
Reputation: 4742
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);
});
}
}
});
Upvotes: 2