My First Shot at Adaptive Images

One of the first problems you run into when trying to build an adaptive layout is that images, unlike blocks of text, have fixed widths. Ideally we want to use small images on small screens and full sized ones on larger screens. The browser can resize the image on the fly, but the two problems with this are: 1) on Windows systems, the  quality degrades when the browser scales the image; and 2) Mobile users shouldn’t have to download a large image, only to scale it down. That takes much more time and bandwidth than necessary.

There are half a dozen popular solutions to this, but I wasn’t completely happy with any of them on their own, so I’m experimenting with using a combination of  Ethan Marcotte’s max-width technique and a modified version of Keith Clark’s cookie technique. The cookie technique can be used to determine the size of a user’s screen before outputting the filename, so you can serve a low-res version to mobile devices and a high-res version to desktops. You can add the max-width technique on top of that to handle any situations where the image still doesn’t fit right.

My modification to Keith’s technique is that instead of setting the image’s src tag to call a PHP file which outputs the respective image’s contents, I just have the function determine the path of the appropriate image. That avoids the faux URL and any caching issues. The image quality will still degrade when it has to scale, but serving multiple images minimizes the number of times that occurs. The major downside is that the it only takes effect after the first page load. But, given the lack of a proper solution, I think that’s an acceptable compromise.

Update: I’m now also considering adding a third layer to help minimize the cases where the first load would include the large images. The browser doesn’t send the screen width with the HTTP request, but it does send a user agent string. The code could parse out the agent and default to the small images for known mobile browsers. On it’s own user agent detection is insufficient, but it may be useful as one of many layers. There could be issues with unreliable (or intentionally false) agent disclosures, and also with different devices using the same agent even though they have different screen capabilities, so it’ll have to be tested out thoroughly, but I think it’s worth a shot.

Leave a Reply

Your email address will not be published. Required fields are marked *