Responsive Image Techniques

Say you have a responsive website design that very image intensive, as I did recently. You want to ensure the clients images come across clear and sharp on all devices, but you don’t want to have to worry about mobile devices needlessly loading in larger versions of the image that they won’t end up displaying.

Given the slow pace of modern browser adoptation, it will be years before we’re able to widely support to the proposed <picture> and srcset solutions. But here’s a quick look at how these they will work.

The picture element wraps a list of one or more <source> elements declaring a media query and a srcset.
The comma seperated list in the srcset attribute indicates the name of the file to load depending on the pixel density ratio of the display: `large.jpg` for normal screens, `large-@2x` for Retina displays. Below the `source` elements is a fallback image. With this markup, we can expect the following behavior:

  • Mobile devices would load small.jpg
  • Screens larger than 600px load large.jpg,
  • Screens larger than 600px with a screen pixel density ratio of more than 2.0 would load large-@2x.jpg
  • Devices that do not support the picture element will load the small.jpg image by default.

Luckily, through a combination of polyfills, we can reproduce rough the same effect.

DPI

Enter Picturefill.js

Picturefill.js is a Javascript polyfill available in two flavors: Version 2, which mimics the approach used by the <picture> element for use in the here and now and Version 1,
which uses <span> elements and custom data attributes to accomplish the same behavior. Here’s what Picturefill 1.0 looks like in action.

Practical Usage

A lot of my work at Doejo involves building sites on WordPress. Naturally, clients tend to manage these sites on their own after launch and it’s impractical to expect them to upload both a normal and Hi-DPI version of each image they upload in the Media Uploaded.

To assist in the process, I like to install WP Retina 2x. This plugin will generate both versions of on an image in each of the themes specified image sizes, when provided with a quality high resolution source image. WP Retina gives you several options for configuration and my preference is to use the Retina.js option. Retina.js will determine if a visitor is using a Hi-DPI device and if so, will attempt to load Hi-DPI version of each image, assuming they’re named with the standard ‘-@2x’ suffix convention.

So what does that mean? It means we can leave off the redundant data-src <span>s for the Hi-DPI images and get a much cleaner, DRY-er code block.

Now, let’s throw in some WordPress.

Filed in: Web Development

Bryan Paronto - Engineering
Comic buff, open source contributor. Cinnamon Toast Crunch.