Question

We are trying to implement infinite scroll in our existing website. Currently we have a image 'click for more' and it makes a ajax call to a method GetArticlesFromNextSection(true) which returns data which we append in #sectionArticles. And this works perfect.

Now we are trying to make it automatic as when user reaches at the end it should make a call to GetArticlesFromNextSection(true) method to load next chunk. Here is what we are using:

<script type="text/javascript">
    $(window).scroll(function () {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            $('#lnkShowMore1').trigger('click'); //click image or
            //GetArticlesFromNextSection(true);
        }
    });
</script>

The problem with above code is, it makes continuous call to method GetArticlesFromNextSection(true) until no data left to load from database. It should make a single call to method GetArticlesFromNextSection(true) and stop and when user tries to scroll again, it should next chunk.

How to make this possible?

EDIT

I used flag but it loads just one time and never again. This is not infinite loop, it should load another chunk again when user reaches end. This is what I used:

<script type="text/javascript">
    var is_loading = false;
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() >= $(document).height() -300) {
            if (is_loading) {
                return;
            }
            is_loading = true;
            //$('div#more').show();
            $('#lnkShowMore1').trigger('click'); //click image or
            //GetArticlesFromNextSection(true);
            //$('div#more').hide();
        }
    });
</script>
Was it helpful?

Solution

Take a look at the answers for How to rate-limit ajax requests?

You can either include and use Underscore's _.throttle() in your script, or take a look at how they implement it and adapt into your code instead of including the whole library for a single purpose.

EDIT:

Using Underscore, your code might look like this:

<script type="text/javascript">

$(window).scroll(_.throttle(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        $('#lnkShowMore1').trigger('click'); 
    }
}, 1000));

... which should rate-limit the requests to once every second.

OTHER TIPS

You can set a flag that check if the content is loaded.

<script type="text/javascript">
$(window).scroll(function () {
    if (!isLoading && $(window).scrollTop() == $(document).height() - $(window).height()){
    isLoading = true;    
    $('#lnkShowMore1').trigger('click'); //click image or
        //GetArticlesFromNextSection(true);
    }
});
</script>

And inside Ajax callback sets

isLoading = false;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top