How to Implement Lazy Loading in JQuery with Ruby on Rails

Lazy load Images in a Rails application
loading of images

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?

Why do we Require Lazy Loading?

How does Lazy Loading 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. We will use the following Lazy load images in Javascript example –

Further Reading: Improve React App Performance by Lazy Loading ReactJS Components!

Technology stack:

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 2: add in your gem file: gem “lazyload-rails”

Step 3: $ bundle install

Step 4: create a new file in app/assets/javascripts/jquery.lazyload.js and grab the lazyload.js plugin.

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 find the complete code on Github here.

You can test this sample App on Heroku :

Note: Press ctrl + shift + r for viewing the better lazy loading of images

https://lazy-loading.herokuapp.com/

That’s it!

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!

Related posts

How To Create Custom Shopify App With Rails?

byNishant Upadhyay
7 years ago

Why Popular FinTech Startups Use Ruby on Rails for Backend

byShardul Bhatt
3 years ago

How To Extend Float Class in Ruby

byChetan Tomar
8 years ago
Exit mobile version