Last Updated: September 09, 2019
·
7.576K
· flexbox

Ruby on rails image helper for retina display with foundation interchange

Deal with retina images could be a nightmare in front-end code.

According to me, the best solution when you work with foundation is to use Interchange.
This javascript library uses media queries to load the images that are appropriate for a user's browsers, making responsive images a snap.

If you read the documentation, the component utilizes the data-interchange attribute for specifying your media queries.
Description

The classic way

= image_tag('front/static/logo.png', alt: 'Description', 'data-interchange' => "[#{image_path('front/static/logo@2x.png')}, (retina)]")

You write the same image path 2 times...
Not really good for your mental health.

The ninja nindô

Simply put this code on your application_helper.rb

module ApplicationHelper
  def retina_image_tag(default_name, options={})
    retina_name = default_name.gsub(%r{\.\w+$}, '@2x\0')
    image_tag(default_name, options.merge('data-interchange' => "[#{asset_path(retina_name)}, (retina)]"))
  end
end

Magic ! use retina_image_tag('front/static/logo.png') to do the job

If you want to use another library for retina images retina.js could be a solution.

2 Responses
Add your response

Hey.

I've taken your method and done this to it :

def retina_image_tag(default_name, options={})

    retina_name = default_name.gsub(%r{\.\w+$}, '@2x\0')

    image_tag('', options.merge('data-interchange' => "[#{path_to_image(default_name)}, (default)], [#{path_to_image(retina_name)}, (retina)]")) \
    + \
    "<noscript>#{image_tag(default_name, options)}</noscript>".html_safe
end

This does:

1) Use path_to_image instead of asset_path so it works with images that aren't in the asset pipeline

2) Don't load the default image regardless of display state - always use interchange to load the image via javascript and only if javascript is disabled use the default image as the image src. Should save on bandwidth on retina devices.

Hope this is helpful :)

over 1 year ago ·

Hello @deanWombourne

This is great! Thanks for sharing

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip