ruby-on-rails-5turbolinksjquery-lazyload

Lazyload not working on Turbolinks page refresh (but works on normal page refresh)


I'm trying to implement Lazyloading of images in my RoR web app, which uses Turbolinks.

I've implemented this gem: https://github.com/jassa/lazyload-rails

It works perfectly as intended if I do a "hard" refresh of the site (which triggers document.ready), but it does not load if the page is loaded by Turbolinks.

I tried changing this code in the jquery.lazyload.js file (line 163):

    $(document).ready(function() {
      alert("Loaded");
        update();
    });

to

    $(document).on('turbolinks:load', function () {
      alert("Loaded");
        update();
    });

But I don't get any alerts in the browser when I do a Turbolinks page load, which makes me believe the lazyload script itself doesn't even get triggered when the page is loaded using Turbolinks.

This is my application.js

//= require jquery2
//= require popper
//= require bootstrap
//= require rails-ujs
//= require turbolinks
//= require libs/dropzone.js
//= require Chart.bundle
//= require chartkick
//= require font_awesome5
//= require jquery.lazyload
//= require_tree .

$("img").lazyload();

And this is how I call lazyload on the image

<%= image_tag f.image, lazy: true %>

Solution

  • Found the solution myself.

    The application.js file only gets called upon a hard refresh, so when the page is loaded via Turbolinks it did not call the $("img").lazyload() function. Solved it by adding this line to the header in the application.html.erb file:

    <script>
      $(document).on('turbolinks:load', function () {
        $("img").lazyload();
      });
      $('document').ready(function(){
        $("img").lazyload();
      });
    </script>