Vinand Vinand - 14 days ago 7
Javascript Question

How to make one ajax request instead of multiple on endless scroll implementation

I load every next 10 publication to the feed, when user scrolls to the bottom. The problem is ajax sends multiple requests since this code detects multiple scroll-to-bottom events. How to make one ajax request instead of multiple, considering that user scroll further down?

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {

$.ajax({
url: '/more/',
type:'GET',
dataType: 'json',
data:2,
success: function (data) {
alert(data);
}
});
}
});

Answer

Use a lock to check if ajax is still in operation and till then don't make next ajax call till you receive data through ajax, after which you can free the lock.

var lock = false;

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {           

if(lock==true){
return;

}

lock = true;        

$.ajax({
            url: '/more/',
            type:'GET',
            dataType: 'json',
            data:2,
            success: function (data) {
                alert(data);
                lock = false;          
            }
        });
    }
});