什么'当内容用完时,这是结束无限滚动的最有效方法

What's the most efficient way to end an infinite-scroll when running out of content?

本文关键字:无限 结束 滚动 方法 有效 什么      更新时间:2023-09-26

我们有一个web应用程序,当我们到达页面底部时,我们会自动加载更多内容,如下所示:

$window
.on('scroll', function () {
    var 
        $this = $(this)
    ;
    if ($this.scrollTop() == $document.height() - $window.height()
        && $('#product-list').hasClass('has-more')) {
        // load more content
    }
})

我们目前在父元素上使用"has-more"类,当没有更多可用内容时,该类将被删除。

我对这种方法不太满意,知道吗?

与其在没有其他内容的情况下删除类has-more,并(仍然)在滚动事件中继续检查它的存在,为什么不删除事件处理程序本身呢?

这样,您就没有事件处理程序,也没有决策,直到您再次绑定它,当其他一些ajax事件消息告诉您现在有可用的内容时。

您可以设置&检查作用域中的变量。所以你的例子应该是:

!function() {
    var hasMore = true;
    $window.on('scroll', function () {
        var $this = $(this);
        if ($this.scrollTop() == $document.height() - $window.height() && hasMore) {
            // load more content & set hasMore to false if applicable 
        }
    })
}();

这里唯一的问题是在页面加载上设置hasMore。您可以在页脚中写入hasMore,而不是像我所做的那样(将其放入一个自执行函数中)。这取决于你。

这种方法可以避免将类名重载为布尔值,并可以节省查询DOM的成本(尽管它非常小)。