Rails 6.1 adds config option to control image_tag loading attribute

Page load times are proportional to the amount of data that needs to be rendered on the screen. So reducing the page size will reduce page load time as well.

According to HTTPArchive, images are the most requested asset type for most websites and usually take up more bandwidth than any other resource. So it goes without saying that one of the first elements to be sacrificed for better load times are the use of images!

But it isn’t always optimal to do that.

With lazy loading of images, the initial load of the page does not request images. Only as the relevant portion of the screen comes into view, the respective images are loaded. This usually involved complex JavaScript packages to be installed. Fortunately, with Chrome 76 onwards, you can use the loading attribute to lazy-load images without the need to write custom lazy-loading code or use a separate JavaScript library.

<img src="image.png" loading="lazy" alt="…" width="200" height="200">

Here are the supported values for the loading attribute:

  • auto: Default lazy-loading behavior of the browser, which is the same as not including the attribute.
  • lazy: Defer loading of the resource until it reaches a calculated distance from the viewport.
  • eager: Load the resource immediately, regardless of where it’s located on the page.


Prior to Rails 6, the loading attribute had to be updated for every img tag. This was incredibly tedious to do, especially if adding this functionality to an existing application.

<%= image_tag "image.png", loading: "lazy", alt: "…", width: "200", height: "200" %>


This commit adds a configuration option to define the default value of the image_tag :loading option. Thus by setting, config.action_view.image_loading an application can opt in to lazy loading images sitewide, without changing view code.

Rails.application.config.action_view.image_loading = "lazy"

Now there needs to be no updates to the image_tags across your source code.

<%= image_tag "image.png", alt: "…", width: "200", height: "200" %>

Will now render out the following HTML,

<img src="image.png" loading="lazy" alt="…" width="200" height="200">

Need help on your Ruby on Rails or React project?

Join Our Newsletter