Last Updated: November 13, 2018
·
1.373K
· bohdanben

Retina image optimization in Ruby on Rails

There is no need to load big images if page is not opened on high-resolution display. In this tutorial we will use a fork of retina-js gem . Basically, this is a wrapper of Retina.js that helps you to easily use it in ruby on rails.
From Retina.js docs:

How it works:
When your users load a page, retina.js checks each image on the page
to see if there is a high-resolution version of that image on your
server. If a high-resolution variant exists, the script will swap in
that image in-place.

The script assumes you use Apple's prescribed high-resolution
modifier(@2x)
to denote high-resolution image variants on your server.

For example, if you have an image on your page that looks like this:

<img src="/images/my_image.png" />

The script will check your server to see if an alternative image
exists at this path: "/images/my_image@2x.png"

To use this gem in your application follow these easy steps:

  1. Add gem 'retinajs-rails', git: 'https://github.com/bohdanbenov/retinajs-rails.git' to your Gemfile.

  2. Run bundle install command in your terminal

  3. Include retina.js file with this tag <%= javascriptincludetag 'retina.js' %> on page where you need to use images optimization.

  4. Add your pictures with high resolution (append @2x after name and before extension) in the same folder with your small image. E.g if your smaller image is in assets/images/flowers.png then your big image should be assets/images/flowers@2x.png

  5. Include your images with tag image_tag_with_at2x to view. E.g = image_tag_with_at2x "flowers.png"

  6. Check if it works. For this, make hard reload of your page and find your images in Network tab. Look at image size. Make bigger resolution (e.g 2560x1600) in chrome dev tools and make hard reload again. Check size again. It has to be bigger than the previous one. Apart from this, there should be changes in html structure of img tag, attribute src should change to your_image@2x.png which indicates everything is good.