Search code examples
javascripthtmljqueryjquery-eventsinfinite-scroll

Wait Until Infinite Scroll Finishes Loading - Javascript


I'm working with an "infinite scroll" page that calls up to 40 elements at a time when a user scrolls to the bottom of the page. How do I detect the moment at which all the content of the most recent set has been loaded?

This only works for initial page load:

$(window).load(function() {
    // Do something
});

Is there something similar for when there's a "load" long after the page has already been done loading?

Sorry if this is a repeat of another question. I was unable to find a solution anywhere else.


Solution

  • After some more digging around, I've used a variation of this question/answer.

    My end result looks something like this:

    function ($container, previousCount, callback) {
        var _imgs = $container.find('img'),
            _newImages = _imgs.slice(previousCount), // 'start index' for new images
            imgCount = _newImages.length, // count how many new ones exist
            counter = 0;
    
        _imgs.on('load', function() { // Count loaded
            runCallback(20, callback);
        }).on('error', function() { // Count errors, anyway, to reach total
            runCallback(20, callback);
        });
    
        function runCallback(counterLimit, callback) {
            // if counter meets new count or hits counter limit, run callback
            counter++;
            if (counter == imgCount || counter == counterLimit) {
                callback();
            }
        }
    }
    

    Some quirks to why I needed it this way. previousCount can actually be greater than total number of images currently in the DOM, this is because people can jump throughout different portions of the infinite scroll. Because of this, there's also the check for counter == counterLimit.

    Also, I need to run a script when the new set of images is done loading, regardless of whether they succeeded or failed. This is why I'm using, both, .on('load' and .on('error' to run up the count. I noticed that sometimes an image can error out (which is fine in this particular case) and it will throw off the count and never fire the callback.

    ==================

    EDIT 04/27/16: I've since discovered a plugin that can handle this for you and seems to work well (with the exception of several subsequent loads before previous load is done loading). Check out imagesLoaded.