Infinite Scrolling Duplication Prevention

I'm trying to implement infinite scroll for my Instagram-like app. However, the jQuery jode part that renders the next page of messages to be rendered is executed twice.

I tried adding a hack, but this is not entirely effective.

Here is 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 repeated part is obviously a duplicate of the ajax request, so a piece of messages is added twice.

How can I fix this problem?

+1
source share
1 answer

First of all, checking the height of the document depending on the height of the window will not work in some browsers. So instead, add jQuery to check if there is #load_more or any other element that you want to paginate using the new jQuery method called inView . Secondly, use $.active to find out how many active Ajax requests are occurring. if it is 0, you can call an 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); }); } } }); 
+1
source

All Articles