Lazyload 不适用于无限滚动 - Ruby on Rails



我想在Ruby on Rails应用程序中构建一个无限滚动功能。为了实现它,我使用了Stimulus JS(更多信息:此处(、vanilla-lazyload js(更多信息,此处(和pagy-gem(更多信息;此处((包括webpacker(。一切都很好,然而,似乎vanilla-lazyload js停止了无限滚动。

这是我的设置。index视图(我使用HAML(:

%section(class="section section--tight" data-controller="infinite-scroll")
%div(class="section-body")
%div(class="content content--shot")
%div(class="shots-grid" data-target="infinite-scroll.entries")
= render partial: "shots/shot", collection: @shots, cache: true
%div(class="section-pagination")
%div(class="content")
%div(data-target="infinite-scroll.pagination")
!= pagy_nav @pagy

JS控制器-infinite_scroll_controller.js:

import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["entries", "pagination"]
initialize() {
let options = {
rootMargin: '500px',
}
this.intersectionObserver = new IntersectionObserver(entries => this.processIntersectionEntries(entries), options)
}
connect() {
this.intersectionObserver.observe(this.paginationTarget)
}
disconnect() {
this.intersectionObserver.unobserve(this.paginationTarget)
}
processIntersectionEntries(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.loadMore()
}
})
}
loadMore() {
let next_page = this.paginationTarget.querySelector("a[rel='next']")
if (next_page == null) { return }
let url = next_page.href
Rails.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: (data) => {
this.entriesTarget.insertAdjacentHTML('beforeend', data.entries)
this.paginationTarget.innerHTML = data.pagination
}
})
}
}

延迟加载vanilla-lazyload:

// https://github.com/verlok/lazyload
import LazyLoad from "vanilla-lazyload";
document.addEventListener('turbolinks:load', () => {
var lazyLoadInstance = new LazyLoad({
elements_selector: ".lazy",
cancel_on_exit: true,
use_native: false
});
})

控制器视图:

def index
@pagy, @shots = pagy Shot.is_recent.includes(:user).all
respond_to do |format|
format.html
format.json {
render json: { entries: render_to_string(partial: "shots/shot", collection: @shots, formats: [:html]), pagination: view_context.pagy_nav(@pagy) }
}
end
end 

pagygem网站表示,gem需要设置webpacker,[这里是链接][4]。然而,这似乎是turbolinks中的问题。换句话说,vanillay-lazyload处理前10条记录,但是,对于新添加的(分页页面中的记录(记录,它拒绝工作。也许我错过了什么?谢谢你的帮助和时间。

JS控制器-infinite_scroll_controller.JS:

更新loadmore函数,Rails.ajax调用成功后,再次运行LazyLoad

在下方添加新代码

new LazyLoad({
elements_selector: ".lazy",
cancel_on_exit: true,
use_native: false
});
loadMore() {
let next_page = this.paginationTarget.querySelector("a[rel='next']")
if (next_page == null) { return }
let url = next_page.href
Rails.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: (data) => {
this.entriesTarget.insertAdjacentHTML('beforeend', data.entries);
this.paginationTarget.innerHTML = data.pagination;
new LazyLoad({
elements_selector: ".lazy",
cancel_on_exit: true,
use_native: false
});
}
})
}

最新更新