Tony Edwards

Lazy load images in a Rails application

- 2 mins

For a recent project I decided to add lazy loading images to improve page load time on mobile devices. It also has the added benefit of reducing calls to the server if the user navigates to another page before all images are loaded. Here’s a quick guide to adding this feature to a Ruby on Rails application.

We’re going to use the Lazyload-Rails gem to benefit from Rail’s developer friendliness. Open up your gem file and add:

gem 'lazyload-rails'

and run

bundle install

Next we need to include the jQuery plugin. Head over to the project repo, grab the lazyload.js plugin. Place this in the javascripts folder of your project and add the following require to the application.js file like so.

// = require lazyload.js

This adds the file to the asset pipeline, preventing an extra request. Next, add the parameter lazy: true to any image tag that you’d like to lazy load. You will end up with an image tag like this:

image_tag "image.png", alt: "It's an image", lazy: true

With every thing in place its time to fire the jQuery method. Open up script.js, or the equivalent for your project, and add this within the document ready call.

$("img").lazyload

This is our minimum viable implementation. It will apply lazy loading to every image on the site. Go ahead and try it out to see if its working. Bear in mind that if you are running the project locally the images will load super quickly. To test it properly, I’d suggest throttling to your connection to simulate a mobile device. Open up Chrome dev tools and click on the mobile phone icon. Select a device (in this case iPhone 6) and change the network drop down to ‘Regular 3G’.

[resp_image id=’388′]

This is great for an MVP, but I’d like to have less of a delay before the image is loaded. Thankfully Lazyload.js has a bunch of helpful parameters that we can use. We’re going to use fadein and threshold. Alter the call from script.js to the following.

$("img").lazyload({
    threshold : 500,
    effect : "fadeIn"
 });

This will trigger the loading of the image when the img tag is 500px below the bottom of the screen and trigger the jQuery fade effect once loaded. Fancy eh? You can look at the Lazyload.js documentation for more details on the available parameters.

Thats it. We now have lazy loading images in our project, a much faster load time and a slightly less stressed sever.

If you need any help with this tutorial, drop me a message on Twitter, I’d be glad to help.

rss twitter github youtube instagram linkedin stackoverflow mastodon