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.

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 it begin

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!

Technology stack:

Ruby 2.5.1p57, Rails 5.2.4, jQuery Lazy Load Plugin

Step 1: Create a new rails application

code 1

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.

code 2

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:

Code 3

Step 7: create a post controller and in routes.rb file and add the following.

code 4

Step 8: In your Post controller add images link :

Code 5

Step 9: In your view file index.html.erb do:

Code 6

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.

Click here for more details…

Consulting is free – let us help you grow!