Responsive & Retina Images on (plain) Ruby on Rails
Devices come in a variety of sizes and configurations. Some have higher pixel density. Sometimes for a given device, we need to load different images based on the width. For handling resolution Retina JS was useful. However, I personally used my own custom JS setup written to work with TurboLinks events and some supportive Rails view helpers bundled into private gem fluid-images.
But those days are long gone. There is srcset
for the rescue and it is supported by all major browsers except Opera Mini.
Before you complain, I know, I am late for the show. I have been very busy implementing APIs, 3rd party integrations, DB optimization, web crawlers, and mobile application development.
Examples
Plain HTML example of how it should look like to show an Retina image:
<img
alt="RailsLaundry Register"
title="Register"
src="/images/register.png"
srcset="/images/register@2x.png 2x"
class="img-fluid" />
Rails 5.2 & 6 have support for srcset
in the image_tag
helper. The above can be written in ERB as:
<%=
= image_tag(
'register.png',
alt: 'Rails Laundry Registration',
title: 'Create New Registration',
srcset: { 'register@2x.png' => '2x', 'register@3x.png' => '3x' },
class: 'img-fluid',
)
%>
The srcset
also allows specifying widths.
<%=
= image_tag(
'register.png',
alt: 'Rails Laundry Registration',
title: 'Create New Registration',
srcset: { 'register_480w.png' => '480w', 'register_800w.png' => '800w' },
sizes: "(max-width: 600px) 480px, 800px",
)
You can find more information here
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.