11

retina.js looks for an image with the same filename but with @2x before the file extension

The rails asset pipeline adds a cache busting timestamp to the end of the filename

This means retina.js is looking for filename-cachebuster@2x.png but the file is at filename@2x-cachebuster.png

Anyone have a work around for this?

Who's wrong on this ie, should retina.js be trained to look for files at filename@2x-cachebuster.png if the original filename matches a pattern that indicates it has a cache busting hash, or should the rails pipeline be changed to ensure the @2x is always just before the file extension?

msaspence
  • 1,424
  • 2
  • 14
  • 25

3 Answers3

5

This seems like a bit of work around in and of itself but looks like the correct way to do this is:

<%= image_tag('image', retina: true) %>

and this will add the correct data-at2x attribute that retina.js will pick up

msaspence
  • 1,424
  • 2
  • 14
  • 25
  • 1
    It's not adding that attribute for me - only add the `retina="true"`. – sergserg Oct 16 '13 at 02:54
  • 1
    This doesn’t seem to be a built-in Rails feature, I assume @msaspence is using [retina_rails](https://github.com/jhnvz/retina_rails). @justin-tanner’s answer below works if you are using [retina.js](http://retinajs.com). – Frederik May 19 '14 at 18:43
5

The retina.js documentation suggests using a rails helper method:

def image_tag_with_at2x(name_at_1x, options={})
  name_at_2x = name_at_1x.gsub(%r{\.\w+$}, '@2x\0')
  image_tag(name_at_1x, options.merge("data-at2x" => asset_path(name_at_2x)))
end

For more information check the retina.js documentation.

Also make sure you have the latest version of retina.js, supporting the data-at2x attribute.

Justin Tanner
  • 14,062
  • 17
  • 82
  • 103
  • 1
    This only works for images whose paths are defined in code or a view. See my answer for a way to solve it from CSS-land with a simple LESS mixin. – Chris Cashwell Oct 24 '14 at 15:26
1

For anything other than an image tag (i.e. CSS background images, which are much more widely used than img tags in most apps I've worked on), I've solved it by writing a little LESS helper which works like a charm.

.at2x(@path, @w: auto, @h: auto) {
  background-image: image-url(@path);
  @at2x_path: ~`"@{path}".replace(/(.*)\.([^.]+)$/, "$1@2x.$2")`;

  @media all and (-webkit-min-device-pixel-ratio : 1.5) {
    background-image: image-url(@at2x_path);
    background-size: @w @h;
  }
}
Chris Cashwell
  • 22,308
  • 13
  • 63
  • 94