This project integrates the pure vanilla JS Layzr Plugin for Rails image_tag helpers
From the project page:
A small, fast, and modern library for lazy loading images, its written in vanilla JS so don't need any Jquery or other js library.
See live demo.
Add it in your gemfile
gem 'layzr-rails'Create a configuration file and put it in your initializers config/initializers/layzr.rb
Layzr::Rails.configure do |config|
config.placeholder = "/assets/some-default-image.png"
endAdd Layzr js and require layzr library in application.js ie:
//= require layzrAnd place the javascript code:
$(document).ready(function() {
const instance = Layzr()
});- Add
lazy: trueoption to Railsimage_taghelpers to render layzr-friendly img tags. - Simple (really). That's pretty much it.
<%= image_tag "kittenz.png", alt: "OMG a cat!", lazy: true %>Equals:
<img alt="OMG a cat!" data-normal="/images/kittenz.png" src="/assets/some-default-image.png"><%= image_tag "normal.jpg", lazy: true, layzr: { retina: "retina.jpg", srcset: "small.jpg 320w, medium.jpg 768w, large.jpg 1024w"} %>Equals:
<img src="/assets/some-default-image.png" data-normal="normal.jpg" data-retina="retina.jpg" data-srcset="small.jpg 320w, medium.jpg 768w, large.jpg 1024w"> Layzr-Rails is released under the MIT License.