Anton S.
Anton S.

Reputation: 1029

Lazyload doesn't work with infinite scrolling - Ruby on Rails

I want to build an infinite scrolling functionality in my Ruby on Rails application. In order to achieve it, I use Stimulus JS (more information: here), vanilla-lazyload js (more information: here) and pagy gem (more information: here) (including webpacker). Everything works great, however, it seems like vanilla-lazyload js stops working on infinite scrolling.

Here is my setup. index view (I use 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 controller - 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
      }
    })
  }
}

Lazy loading 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
    });
})

Controller view:

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 

The pagy gem website says that the gem requires a setup for webpacker, [here is the link][4]. However, it seems like the problem in turbolinks. In other words, vanillay-lazyload works with the very first 10 records, however, with newly added (records from paginated pages) records, it refuses to work. Perhaps I am missing something? Thank you for your help and time.

Upvotes: 1

Views: 722

Answers (1)

Vu Vy
Vu Vy

Reputation: 368

JS controller - infinite_scroll_controller.js:

Update loadmore function, after Rails.ajax calling success, run LazyLoad again

Add new code below

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
        });
      }
    })
  }

Upvotes: 1

Related Questions