简体   繁体   English

等待无限滚动完成加载-Javascript

[英]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. 我正在使用“无限滚动”页面,当用户滚动到页面底部时,该页面最多调用40个元素。 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. 我在其他任何地方都找不到解决方案。

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. previousCount实际上可以大于DOM中当前的图像总数,这是因为人们可以跳过无限滚动的不同部分。 Because of this, there's also the check for counter == counterLimit . 因此,还需要检查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. 这就是为什么我同时使用.on('load'.on('error'来计数的原因。我注意到有时图像可能会出错(在这种情况下很好),它将放弃计数,从不触发回调。

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

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). 编辑04/27/16:从那以后,我发现了一个可以为您处理此问题的插件,并且似乎运行良好(除了之前加载完成之前的几个后续加载)。 Check out imagesLoaded . 检出imagesLoaded

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM