OpenSourceVarsity

pdf icons

Delivering Responsive Images – The Challenges

As a website developer you must be getting multiple requests to build responsive websites from clients. I’m sure you’ve noticed this trend. Today, almost every website owner wants to have a website that is accessible to site visitors using a plethora of display sizes. From tiny Android based smart phones right up to 24 inch desktop displays. Website owners are demanding a uniform quality of site visitor engagement and visual experience.

AND

They just do not want multiple websites. One site for mobile devices, one website for tablets and Pablets (i.e. Phone tablets like the Samsung Galaxy Note and others), one website for netbooks and notebooks and another for laptops and so on. This is really a maintenance and content updation nightmare. No website owner is going to accept such a solution today.

All mobile friendly websites are normally built using a responsive framework like Bootstrap. It’s the responsive framework, which ensures that the website’s content is flexible enough to adjust automatically, and display content accurately, across display devices associated with smart phones to the 21 inch desktop.

Having said that, what’s also going to be needed is an excellent responsive image solution for the website.

Scaling Of Website Images Displayed

Scaling images to display correctly across display devices of different sizes and pixel densities is only one half of the issue to be resolved.

The other perhaps more tricky set of issues are:

  • Controlling the download image size as the display size reduces sharply
  • Controlling the total download time taken
  • Most importantly perhaps would be picture details being lost dramatically when a large image is resized using a media query

There are several responsive image solutions to choose from. Each solution comes with its own strengths and weaknesses unfortunately not one of them is a perfect wholesome solution.

This material attempts to leads you through the basics of delivering responsive images as web page content for a responsive website. Subsequently, it will provide you with specific information needed to pick the best responsive image solution that would work for your website.

Responsive Images – The Basics

Styling foreground images to adjust to the width of their container is very easy. Bootstrap 3 provides a class named img-responsive that should be added to the <img tag as follows:
<img src=””  alt=” “ class=”img-responsive”>

In most cases, this simple img tag style rule works perfectly. If the container (<div></div>) holding the image becomes narrower than the width of the image, the Browser will scale down the image to match the width of its container. Setting the class=”img-responsive” ensures that the image does not scale larger than the container’s actual size.

NOTE: On small screen sizes this approach would make the image quality terribly grainy.

Regretfully, the high-resolution, Retina images in demand today can make this basic sort of image responsiveness approach tricky.

Let’s say you want your 150 × 150-pixel logo to display at double the usual pixel density, and the image is small enough that having two separate versions would not be a problem.

So, you create a 300 × 300-pixel version of the logo and plug it in the pixel density and size of such an image would be huge hence, you might try adding a styling rule to the styles sheet as the one below.

img.sitelogo
{
    max-width: 150px;
}

This does not work as expected. Since the image max-width is specified in pixels the logo image now refuses to scale nicely with the other images on the webpage.

To limit the maximum width of an adaptive image, one has to limit the maximum width of the image container, rather than of the image itself.

Let’s say the webpage logo is wrapped in a container <div></div> which is bound the class logo.

Then this style rule will work:

.logo 
{
    max-width: 150px;
}

For now it appears that scalable responsive images do exist in our webpage. Unfortunately, there are still two issues that are not yet addressed.

The Webpage Performance Problem

With the above CSS style rules, all display devices (remember the smart phones to 21 inch desktop display devices) are fed the same images by the webserver.

For small icons and logos this might not be too bad, but as the images get larger and heftier the time taken for the image to download becomes an issue. Retina quality images make the download time issue worse.

What is the point of downloading a huge Retina image to a device that is incapable of displaying such detail appropriately?

Think about it. Must we ensure that a 990 × 300-pixel 100 KB image, meant for desktop viewers is downloaded to a smart phone?

The mobile visitor might using a coffee shop’s Wi-Fi connection alternatively, they might be on the road trying to get crucial information from your webpage website, with one shaky bar of 2G or 3G wireless service.

Every mobile user who gives up when your webpage takes too long to load is a potential customer, and potential income lost forever.

Adding To Webpage Load Time Problems – Browser Preloading

Logically it would seem that a simple solution to this issue would be to have identical images of different sizes and/or pixel densities and load them from the webserver into the webpage using appropriate media queries.

The idea being that the appropriate media query would fire and based on the CSS rules contained within the correct size of image would be downloaded from the Webserver and inserted into the webpage.

How I wish it was that simple. Regretfully it’s not.

Here is why:

The problem is in order to provide the fastest webpage downloading time possible, Browsers preload all of the images that they can identify in the HTML4/5 source code before any CSS or JavaScript is processed.

Hence, using media queries to display the right sized image in a mobile device actually penalizes such site visitors using mobile devices a whole lot more, by ensuring that the Browser on their mobile device downloads all of images of varying sizes first and only subsequently rendering the webpage in their mobile device.

NOTE: Because of this nasty built in habit of Browsers preloading images, most responsive image solutions require either a Webserver side solution (that preempts such preloading) or special HTML markup and JavaScript.

Adding To Webpage Load Time Problems – Bandwidth Detection

The last piece of the mobile device, performance issue is network speed. Obviously large images should to be delivered to devices that are on a fast network. Everyone today has experienced the snail’s pace of downloads via 2G networks when compared to the download speed of 3G networks.

Regretfully as on date, there is just no fool proof, accurate way, to determine network download speed. Foresight.js uses JavaScript to test how long the Browser takes to download a 50K image. Then stores that information and uses it to make bandwidth decisions.

Here is the drawback:

This approach adds a 50K image download to each webpage. This can block the download of other images on the webpage until the test image download is complete. Many of the responsive image solutions that currently implement bandwidth detection use a variation or adaptation of Foresight.js.

The Art Direction Problem

Assume you have a wide image on your home page, which displays an expanse of fields and forest, blue sky and fluffy clouds above, and a happy family having a picnic on the grass. If the same image is scaled down to fit a smart phone, the vacationing family looks more like the ants at the picnic or are not visible at all as shown in diagram 1.

Diagram 1

This is what is politely called the art direction problem. Some http://www.opensourcevarsity.com/images just cannot be auto scaled well. Fine detail is lost, and dramatic impact gets thrown to the winds.

In the case of this image, it would be much nicer visually if the mobile version of the photo zoomed in, cropped and focused on the family having the picnic. To solve such issues a responsive image solution is required that enables the web page developer to specify different versions of the image for different display sizes as shown in diagram 2.

Diagram 2

Some Responsive Image Solutions That Are Tried & Tested

Picturefill a JavaScript library used as is a polyfill for the proposed <picture> element in HTML5. This JavaScript code mimics the picture API, enabling web page developers to use it on websites today.

Picturefill does not require jQuery, but does require the picturefill.js script to be included somewhere in the webpage. Picturefill also requires some special markup, with divs to represent the image variations, differentiated by data-media attributes that act just like media queries in CSS.

One can optionally put an image in conditional comments for browsers that do not support media queries, largely because IE 8 misbehaves with media queries. Use a fallback in a <noscript> tag for browsers that do not have JavaScript enabled such as Blackberry devices.

NOTE: Truthfully, a web developer can go quietly insane trying to deliver a truly responsive web page in older versions of IE. It’s so much easier to politely decline doing such work and maintain your sanity and hair on your head.

Here’s an example of a typical Picturefill block of codespec used to display Responsive Images.

<span data-picture data-alt="Descriptive alt tag">
    <span  data-src="images/myimage_sm.jpg"></span>
    <span  data-src="images/myimage_lg.jpg" data-media="(min-width:  600px)"></span>

<!–[if (lt IE 10) & (!IEMobile)]> <span data-src=”images/myimage_sm.jpg”></span> <![endif]–>

<!– Fallback content for non-JS browsers. –> <noscript> <img src=”images/myimage_sm.jpg” alt=”Descriptive alt tag” /> </noscript> </span>

That’s all you need to display adaptive images at page-loading time using Picturefill.

Drop in the script, configure the markup, and everything just works. You can also call Picturefill programmatically if you need to add images to the webpage on the fly.

NOTE: Picturefill requires a lot of custom markup, so it might not be the best choice for those who cannot alter their website’s source code for any reason. It also does not do any bandwidth detection.

HISRC – Another Responsive Image Solution

HiSRC, is a jQuery plugin that enables a webpage developer to create low, medium and high-resolution versions of an image. The script will show the appropriate images based on two checkpoints Retina-readiness and network speed.

To set HiSRC, ensure that the jQuery Javascript library and HiSRC Javascript library are included somewhere within the webpage code, either at the top between <head></head> or just above the </body> tag within the HTML webpage code.

Within the HTML code, where appropriate:
Add a regular image tag to the page
Set the src to the low-resolution (or smallest) version of the image
Add a class to the image or its wrapper (like .hisrc) to specify which images HiSRC should process.

Then, add some special markup to your image tag:
data-1x
And
data-2x attributes, pointing to the medium and high-resolution versions of the images respectively.

For Example:

<img src="http://placekitten.com/200/100"  data-1x="http://placekitten.com/400/200" 
data-2x="http://placekitten.com/800/400"  class="hisrc" />

Then, after the DOM has loaded, just call the function on the image class that’s being used.

$(document).ready(function()
	{
 		$(".hisrc").hisrc();
	}
);

In practice, the browser will first load the img src i.e. the mobile version of the image.

Then, the script checks to see whether the visitor is using mobile bandwidth (such as 3G). If so, it leaves the mobile-first image in place.

If the connection is speedy and the browser supports a Retina image, then the @2xversion is delivered. If the connection is speedy but Retina is not supported, then the @1x version is delivered.

Notice that the low-resolution image always loads, even if the script later decides that the site visitor’s device is a good candidate for high resolution. This is technically a double-download, however it only penalizes those on speedy connections, which is normally an acceptable compromise.

HiSRC can handle images that are added to the page dynamically. It also allows for multiple images, so you can specify different crops and sizes to beat the art-direction problem.

HiSRC Weaknesses

  • HiSRC does require jQuery, so it won’t be useful unless the jQuery is pinned within the webpage.
  • HiSRC requires custom markup in the HTML, so it might not be the best choice if you have a huge website with a lot of legacy images

OR

  • A CMS in which the output of the image tag cannot be altered

Adaptive Images – A Webserver Side Solution

Unlike the previous two solutions, Adaptive Images is mostly a server-side solution.

It requires a tiny bit of JavaScript, but the real work is done via the Apache 2 Web server, PHP 5.x and the GD library.

To install it on your Web server, you’ll need to:

  • Alter or add a .htaccess file in your domain’s root directory
  • Upload some PHP files to your website’s root directory
  • Add some JavaScript to your webpages (which will add a cookie to record the user’s screen resolution
  • Configure some breakpoint variables in the PHP files to match your website’s media queries

The installation instructions for Adaptive Images is quite verbose. Do visit their official website and click the Details link.

The best feature of Adaptive Images is that it requires no custom markup on any of your images. Once you’ve installed and configured it correctly, you’re all set! The PHP script will:

  • Intercept any request for an image
  • Will resize it on the fly as needed to your specified breakpoint sizes

AND

  • Serve it to the requesting Browser automatically

The PHP has a lot of configurable options, such as image quality, breakpoints, caching, and even a sharpening filter to apply to the generated scaled images.

Adaptive Images Weaknesses

  • Because Adaptive Images requires the combination of Apache and PHP, it might not match up with your website’s platform or be available on your Web host’s server.
  • Adaptive Images relies on the Web server’s ability to intercept any requests for images (via the .htaccess file). So, if your images are hosted elsewhere, such as on a Content Delivery Network (CDN), then it will not work.
  • Does not detect bandwidth.
  • Cannot solve the art direction problem with images, because it only rescales the original images. Adaptive Images cannot crop or create different aspect ratios from the original image.

SENCHA.IO SRC

Previously known as TinySrc, Sencha.io Src is a third-party solution that acts as a proxy for images. One does not need to configure anything on the webserver. Just point to your images at Sencha’s servers (with or without some options specified), and Sencha will process this request correctly and send back a resized version as is needed.

Let’s say there is a big image:
<img src=”http://www.your-domain.com/path/to/image.jpg” alt=”My large image” />

Just prefix the src attribute with http://src.sencha.io/
<img src=”http://src.sencha.io/http://www.your-domain.com/path/to/image.jpg” alt=”My large image” />

By default, Sencha.io will resize your image to fit the width of the display device’s screen, using the user-agent string for detection. Phones might be sent a 320-pixel-wide image, tablets a 768-pixel-wide image, and so on.

The Sencha.io, prefix string, can also be configured to return particular measurements, orientations, percentage sizes or any number of complex calculations. Sencha.io is a free service for individual users. Hence, it can be a very convenient adaptive image solution.

Ensure Extensive Website Testing Is Done

After one has chosen and implemented a responsive image solution, testing the performance of the website is absolutely necessary to making sure that the solution is working well. Here are some useful online testing tools that would be of great help.

YSLOW

Created by Yahoo, YSlow is a client-side tool that analyzes your website against 23 testable rules that Yahoo has determined can adversely affect Web page performance.

YSlow awards your website a grade for each rule, explaining each one and suggesting how to improve your website’s performance. YSlow is available for Firefox, Chrome, Safari and Opera.

WEBPAGETEST

WebPageTest is an open-source project online tool maintained by Google. Enter the website’s URL, perform a speed test from a chosen location, and specify which browser to use.

Advanced settings the performance of multi-step transactions, pick a network speed (cable, DSL, FiOS, etc.), disable JavaScript, block ads and make other requests, and more.

The results come in the form of tables, charts, screenshots, a performance review and a lot of great data to dig into. The Yottaa blog has an article detailing how they used WebPageTest to test out their website both with and without responsive image loading.

To Conclude

The next time a beautiful, user experience is crafted for your website’s mobile visitors, try out one of these responsive image solutions that take your website the extra mile. Your mobile visitors will have good reason to smile and come back for more.

Now, just to set your mind at rest this is not the only tutorial covering responsive images. This is an introductory tutorial which helps explain the complexities of delivering responsive images to be viewed on different display sizes and the solutions available and in use today.

NOTE: This is by no means an exhaustive tutorial. The challenges faced in delivering Responsive Images to different display sizes is evolving constantly. As new / better solutions get delivered I’m going to do my very best to upgrade this content.

Lessons later in this material cover the code specifics for delivering Responsive Images in webpages.

April 5, 2016
Design by Ivan Bayross and Meher Bala © 2016 All Rights Reserved
X