How to Implement Lazy Loading in JQuery with Ruby on Rails
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.
It will quickly load images after page load in the app. It makes page loading simple during Ruby on Rails rapid application development.
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. We can use jQuery – lazy load images work best with that.
How does Lazy Loading work?
Further Reading: Improve React App Performance by Lazy Loading ReactJS Components!
Ruby 2.5.1p57, Rails 5.2.4, jQuery Lazy Load Plugin
Here are the steps to implement lazy loading in jQuery
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