Lazy load Images in a Rails application
Have you ever found a very simple approach to do lazy loading in your application? Not yet? Let’s start.
I wanted to add lazy loading of images on my website to improve the page load time because it contains too many images when the application is loading for the first time. Here, I have tried some simple logic which helps you to understand how to lazy load image in rails application.
What is lazy loading?
- Lazy loading is an optimization mechanism for the online content of the website.
- Lazy loading is a term frequently used to refer to the concept of loading parts only when it’s needed.
Why do we Require Lazy Loading?
- Loading the entire page of the website and delivering it to the user might take more time to load and can’t satisfy the user for faster content rendering.
- Instead of that, we can do lazy loading which helps to improve rendering required content first and the other after some time using lazy loading.
How does it work?
Let’s start from the very beginning and implement the whole flow to have a brief introduction to lazy load images in rails application.
Further Reading: Improve React App Performance by Lazy Loading ReactJS Components!
Ruby 2.5.1p57, Rails 5.2.4, jQuery Lazy Load Plugin
Step 1: Create a new rails application
Step 3: $ bundle install
Step 5: require this plugin in your application.js
//= require jquery.lazyload
Important: Remember that the Lazy Load Plugin depends on jQuery.
Step 6: Create a new file in your config/initializers/lazyload.rb and add the following code snippet:
Step 7: create a post controller and in routes.rb file and add the following.
Step 8: In your Post controller add images link :
Step 9: In your view file index.html.erb do:
Great !! you are all done. You can test it in your application on how lazy loading works.
You can test this sample App on Heroku :
Note: Press ctrl + shift + r for viewing the better lazy loading of images
BoTree Technologies is a leading software development company in Ahmedabad that builds top-notch software and solutions to increase business revenue and maximize productivity.
Consulting is free – let us help you grow!
Choose Your Language
- Digital Marketing
- IT Consulting
- Project Management
- Salesforce Development