Responsive Images: How they Almost Worked and What We Need
Issue № 343

Responsive Images: How they Almost Worked and What We Need

A note from the editors: Since this article ran in Issue No. 343, author Mat Marquis has established and is chairing a Responsive Images Community Group for the W3C. All are invited to participate.

It’s our job, as designers and developers, to pick apart even the seemingly most simple tasks to find ways to improve them. When Ethan Marcotte coined “responsive web design,” he said that a responsive website is made up of three things: a flexible grid, flexible images and media, and media queries. In doing so, he opened up a world of new and exciting things to obsess over. I chose flexible images.

Article Continues Below

It’s easy enough to style images so that they scale to fit within a parent container by adding img { max-width: 100%; } to one’s stylesheet. To use this effectively, though, the image must be large enough to scale up to whatever size we can reasonably expect on the largest possible display. This can mean a great deal of overhead. At best it’s just wasteful. At worst, the mobile browser stuffs its hands in its pockets and goes to sulk in the corner, leaving the page partially rendered. A handful of full-bleed images designed for a 13” display could bring a mobile device on an Edge connection to its knees.

Unfortunately, we can’t test bandwidth in any reliable way—not yet, at least. Testing would likely mean introducing a significant download to measure against, which is a lot like setting something on fire to see exactly how flammable it is. What we can determine with some reliability is the size of a device’s screen—and while we can’t necessarily use screen size to make assumptions about bandwidth, it does directly correlate to what we’re trying to accomplish: while a browser’s window size may change, we’ll never need an image larger than the user’s screen.

While we were working on the new Boston Globe website, we devised a technique to mitigate the size of requests for users that may have limited bandwidth. Before I describe it here, I should really warn you up front: it broke. But we planned for that.

How responsive images worked#section2

Scott Jehl brilliantly masterminded Filament Group’s “responsive images” technique. We began with the core philosophy that the technique should err on the side of mobile. With a mobile-first approach, if any part of the process should break down the user should still receive a representative image—even if it’s a bit smaller—and avoid an unnecessarily large request on a device that may have limited bandwidth. Progressive enhancement writ large.

There are three key components to our responsive images script: the markup, the JavaScript, and a server-side redirect rule.

We started with, perhaps unsurprisingly, an image tag:

<img src="mobile-size.gif">

With that as our basis, we’re ensuring that we default to a mobile-sized image. We store the path to the larger image in a data attribute for easy access via JS:

<img src="images/mobile-size.jpg" data-fullsrc="images/desktop-size.jpg">

Now that we have both sources in our markup, we need a way to conditionally load the appropriate source. To do that we need to know the size of the user’s screen. Fortunately, there’s a relatively simple way to determine a device’s screen size through JavaScript by way of a property in the browsers’ window object: window.screen.width, though even that isn’t entirely reliable.

Here’s where we run up against a major challenge: we need to communicate this size to the server in time to defer the request for the image’s original src, if necessary. The server needs to know the client’s screen size before our images are displayed.

We eventually settled on setting the screen size in a cookie. A cookie set in the head of a document would be ready in time for the parsing of the document’s body, and included along with image requests.

I assume that you’re cringing at the idea of cookie-dependent functionality, and I understand—I do. Some of our first iterations involved <noscript> tags and document.write. I still have nightmares about dynamically-injected base tags. These were desperate times, and we left no stone unturned.

Our JavaScript’s second task was far more simple: if the screen was above the size we specified, we swapped the img tag’s original src for the path contained in the data-fullsrc attribute and displayed the larger image in place of the smaller one.

Since the screen size was now available to the server, we toyed with a server-side solution that would automatically resize the original image to suit the screen. We decided against this for several reasons:

  • We wanted to keep server-side dependency to an absolute minimum, and only implement something that could be easily recreated in various server environments.
  • Rather than simply resizing an existing image, we felt it was more important to have the flexibility to crop and zoom the larger image in a way that fully optimizes it for display on a smaller screen.
  • Any of the back-end solutions we experimented with involved scaling a large image down to suit the screen size, which creeped us right out. If the screen’s width was reported incorrectly or if the front-end scripting should break down, we would run the risk of subjecting users to a massive and unnecessary download.

The src-swapping part of the JavaScript handles the lion’s share of the work, but larger-screened devices still make redundant requests—first for the mobile image, then the full-size image. This results in a pretty jarring visual effect as well: the smaller image may be visible before the larger one snaps into place. Since the original src is fetched as the browser parses the img tag, we can’t really dodge that request from the client side. What we can do is mitigate those requests on the server side.

We wrote some simple Apache rewrite rules to intercept requests for an image and check for the cookie we set earlier. If the breakpoint conditions we specified were met, we redirected the request for the mobile-sized image to a 1—1 spacer gif. This kept the size of the redundant request low—especially once cached by the browser—and prevented the mobile-sized image from displaying before we swapped it for the full-size image. Since we didn’t want to apply this logic to every image site-wide, we later introduced a second rule that allowed us to flag images as responsive: the logic above only kicks in if the image’s filename contains “.r.”

<img src="images/mobile-size.r.jpg" data-fullsrc="images/desktop-size.jpg">

Thanks to our mobile-first approach, we had ourselves a pretty scrappy little technique. If any part of the equation should fail, no users would be penalized for their context. A failure on the client side—if cookies or JavaScript were unavailable, for example—would result in a smaller, but perfectly representative image. A failure on the server side would mean a request for the smaller image prior to the full-size image, but in a context where we could at least assume greater bandwidth. No one would be left without images regardless of their device, browser, and features.

This is fortunate really, since within a month or so of launching our responsive image approach broke.

What went wrong#section3

Several newer browsers have implemented an “image prefetching” feature that allows images to be fetched before parsing the document’s body. While it’s hard to argue with a quicker overall loading scheme, it goes against the parsing behavior we’ve come to understand. For our purposes, this feature also invalidates all our methods for communicating the screen size to the server before the images are loaded and breaks our server-side redirect. You can see this on right now: without that redirect you’ll briefly see the mobile-size image before the full-size image is loaded, but it may take sharp eyes and a few page refreshes. Fortunately, this additional overhead is only incurred on desktop browsers, where bandwidth is generally less of a concern.

So, now what?#section4

Long after the Boston Globe site launched, we continued to iterate on our approach. Jason Grigsby has done an incredible job documenting the details of those trials and tribulations in a series of blog posts.

This brings us to the present day, with some of the brightest minds on the web looking for something—anything—that will get the job done. Some think that it isn’t a solvable problem right now, and are placing their bets on user agent detection as a temporary solution. While this is a perfectly viable answer in the short term, I maintain that it’s untenable going forward: with the ever-expanding range of mobile phones and tablets in circulation, we could never hope to maintain a reasonable list of browsers and devices for long.

I believe that the ultimate solution shouldn’t hinge on scripting or CSS—and certainly nothing like UA detection, cookies, custom scripting on the front end, or any server-side shenanigans. Our aim is to represent and serve content appropriately, and for that reason I believe that this should be solved in markup.

The img tag isn’t going to cut it for this, though. It’s effective at conveying the hilarious antics of house cats, but it isn’t well suited to complex logic. It does one thing, and it does it well: it takes a single image source, and it puts it on your screen. If we were to modify this behavior at the browser level, we would never be able to guarantee our changes wouldn’t introduce issues in older browsers. We also know from experience that img doesn’t leave us much (if any) room to polyfill this new behavior.

What we need is a new markup pattern—one that allows us to specify multiple source files, but still specify universally-recognized markup as “fallback content” for browsers that don’t recognize the new tag. This should sound familiar, as this pattern already exists: the video and audio tags.

We know that a video tag can contain references to multiple sources, and that we can specify fallback content within the tag that’s only visible to browsers that don’t support video natively—usually a Flash-based video. What you may not know is that there’s already a way to use media queries to determine which video source to use, though browser support is a little spotty.

        <source src="high-res.webm" media="min-width:800px" />
        <source src="low-res.webm" />
        <img src="poster.jpg" />

From there, it doesn’t take much imagination to see how we could use a pattern like this.

        <source src="high-res.jpg" media="min-width: 800px" />
        <source src="mobile.jpg" />
        <!-- Fallback content: -->
        <img src="mobile.jpg" />

We could have a limitless number of options by using source media queries—higher resolution images for high-res displays over a certain size, for example. If we could reliably detect connection speed, one day we may be able to add media=“connection-speed: edge” or media=“min-speed: 200kbps” to our source elements. If these source elements are implemented per the HTML5 spec, a request will only be sent for the ones that match our media query. What we get is a single, highly-tailored request, with conditional flexibility limited only by a constantly growing roster of media queries.

Once we’ve established that markup as our foundation, we may be able to polyfill the expected behavior for browsers that don’t yet support it. While it’s likely that the polyfills would still involve more than one request, starting with a tried-and-true fallback pattern would allow us to apply polyfills at our discretion.

While we’re at it, I’d also like a pony#section5

As things stand now, a number of developers—myself included—are talking with WHATWG and various browser teams about the details of this new element. A frustrated group of developers pitching a need for a new element is certainly nothing new; we’re not the first, and I’m certain we won’t be the last. In fact, we’re not even the first to reach the exact same conclusion on image delivery: after brainstorming, we learned that a solution much like our own was posted to the W3C’s public mailing list in July of 2007—similar right down to the semantics. This subject has come up multiple times on the WHATWG and W3C discussion lists and quietly died out each time, but never during such a radical shift in browsing context as we’ve experienced over the past year or so, and never in such an exciting context as responsive web design.

While we can’t guarantee that a picture element—or something similar, semantics aside—will ever see the light of day, we’ve recognized that there is a need for such a markup pattern at present, and tremendous potential to such an approach in the future. I’d love to hear your thoughts.

77 Reader Comments

  1. A nice solution to harness <video>-like functionality. But rather than some new element like , I’d rather see the element accept multiple sources like video does.

  2. This really hits the nail on the head – the responsive web should live in markup! Developers shouldn’t have to rely on various forms of scripting to achieve what, in theory, is a pretty simple (and increasingly necessary) task.

    In all honesty I would hope by the time something like this was implemented bandwidth limitation issues would be nil; though, all the mobile bandwith caps out there are telling me I’m an idiot.

  3. Hi there,

    there’s a mailing list here: but without my latest proposal (
    So picture element wouldn’t work best as described in mailing list. And we don’t even need a new element in my mind but need only to do it my second way (described in my article). My first approach with attributes would work, too, but is not that pretty.

    So, let’s hope that one of the good solution is coming up soon to the spec. And, by the way, also recognize my CSS3/4 approach which would do the same for layouted styles.


  4. I think Src is a great way to work around a very real problem, but I don’t think it’s our final solution by any means. While they’ve done some incredibly clever things, I can’t really say that routing our images through a third-party proxy feels like “the way forward.” The “Future Friendly”: folks absolutely nail my thoughts on this stuff.

  5. We experimented with souping up img, but it left us with a lot of long-established behavior to work around. Polyfilling any changes to img put us in the same situation as we’re in now, and even though we tested a “downright absurd number of browsers”: to ensure that things would fall back in a predictable way, there’s still the matter of unknown unknowns—if some ancient and arcane Android browser would lose it’s mind over a modified image tag, then we’re penalizing a user somewhere and that’s not okay. We’ve also been told that it’s impossible for a parser to “look ahead” to multiple sources before fetching assets, within an img. That sucker is a big boat to rock, as it turns out.

  6. I’ve heard several people say they are against using user agent detection. Could anyone elaborate as to why?

    Just as HTML/CSS needs to mature to better adapt to different devices, it seems like if the user agent strings matured and became more descriptive they would be extremely useful.

  7. I first ran into this issue about 10 years ago while developing content for mobiles, and about 6 years ago while developing a social network aimed at (pre-smartphone) mobile devices I started using user agent detection as this was the only viable solution I could come up with. I know there’s a lot of them but there are ways around this, with the most obvious one being WURFL and a bit of server-side scripting to keep the database updated.

    The platform I use for building websites now automatically detects the device type (and any needed media size properties) and stores them for the life of the user session (either in a cookie or in a session query string matched to a database record for devices that don’t support cookies) which allows me to implement responsiveness in markup by only ever serving the right image size in the HTML img tags in the first place (as well as sorting out which type of video embed to use, if any).

    Related to this is the subject of bandwidth. One of the key issues I’ve had in building mobile-suitable sites is not actually bandwidth (although this is always an issue), it’s how large a page (combined HTML, markup and images) a device can actually display, with the most visible one being the old Motorola Razr v3. Some versions of this handset had a whole 10k of RAM available for rendering pages. Device detection allowed me to cater for even this restriction by automatically breaking large pages into smaller chunks for delivery to such devices by detecting the device in advance from the user agent.

    However with most modern devices now reporting screen sizes (or easily derivable screen sizes based om generic user agent strings) and it very rare that a non-smartphone is being used to access the sites I build I’m actually finding less need for specific device detection at all.

  8. These are some fantastic methods. As a backend guy, I can plan for and supply the frontend with whatever fields they like, but knowing the possibilities is more important. Thanks for a great article!

  9. @matudnorthrup: I think the article says this in so many words, but while UA detection is probably the best tool for this task at the moment, that doesn’t negate the need for implementation of a standards, simple, front-end approach to this problem. UA is a tool that should never be ignored, but it’s an increasingly complicated tool to use for negotiating situations like this one, especially when you’re trying to build against future browsers rather than working around known issues of past ones. As Mat mentioned, the video and audio elements have already set a nice example of how markup alone can address this very problem, and if we can follow that model, it’ll greatly simplify our job as developers down the road.

  10. Interesting. I wound up doing the same thing with data attributes and javascript, and learned screen size isn’t always a good proxy for how big the images should be. (I have at least one page where the tablet-range layout actually needs a bigger photo.)

    So if we’re going to ask for a pony, how about the one we really want: an API (both js and media query, please) to determine bandwidth.

    Especially as Apple ships devices with denser and denser screens, we’re going to start seeing lot’s of small devices that actually *do* want high res images. On the other side, it’d make a lot of sense of serve high res images to tablets while they’re on WiFi and allow a little fuzziness while they’re on 3G, or dial down image quality for people on overshared coffeeshop connections.

    Obviously it makes an article stronger to make definitive statements such as you would “never” want an image to be larger than the screen displaying it. However, far from never wanting to present an image larger than the screen space available it is perhaps more common to want to display an image which is larger than 1280*720 (currently a large mobile resolution) should such a size be available.

    For example when viewing a number of e-commerce websites I like the ability to zoom into an image to see in finer detail an item I wish to purchase, especially if the item is second hand where detailed portions of the image can be important in the purchase decision. I for example always switch to “classic” mode in ebay in order to make informed purchasing decisions because the mobile images are too low quality.

    Other examples would include re-sharing images between devices (e.g. emailing from a mobile to a desktop machine), printing images to a different sized device, which are severely impacted by serving specific image sizes to mobile devices.

    Your statement is primarily only true when the images are of very little importance to the end user task and perhaps mainly decorative in nature. is wrong in suggesting that the device width will always be more important than the semantic value of the image!

    I did experience problems with the Boston Globe image size and portrait / landscape switching on a Samsung Galaxy S 2.3.5 stock browser and images becoming pixelated when they were not pixeled in Chrome on Windows 7.

    Not sure I have seen a site with “responsive webdesign” that was superior to the “desktop” version, In most cases I regularly use the desktop version of sites on my mobile device.

    Again your suggestion of a bandwidth detector is also problematic for a number of reasons.

    1. Bandwidth is to an extent site specific
    2. Bandwidth does not remove the importance of the nature of the task. Just because the download is slow does not mean the person is not happy to wait for a full resolution image.

    The only real solution is an image format that is designed to download progressively to a specified size and potentially use spare bandwidth to download higher detail levels to allow for smooth scrolling. Essentially images would appear to work in a similar way to Google maps but all image behaviour is contained within the original image file and the code to download the appropriate level of detail is controlled by the server and the browser and is outside the general control of the developer.

  12. Some great theories in here and although none of them can be said to be ‘good’ they are undoubtably preferable to loading a 1000px+ image in to a 320px window 🙂

    My one concern is the bandwidth/connection-type attributes you propose for the img/picture tag. If I’m tethering my mobile with my laptop through Edge,3G,etc (no-so-often) or if I’m doing some heavy up/downloading (often), there may be occasions when I’m patient enough to wait for the full experience. I would at the very least like the option. A device-width query inside the tag (like the video tag) works great for me.

    That said, if the bandwidth/connection-type attributes did get browser support, there’s nothing stopping browsers having a UI ‘Fast Loading On/Off’ option which overrides the attribute value…

  13. Nothing to stop the image formats getting smarter and taking a leaf out of the “icon” book.

    As the decision about bandwidth is actually one for the user – sometimes difficult to tell whether they are on a fat pipe with a tiny device or other way round – much better to let the browser decide what it thinks is best and make an indexed-based request for the bitmap. Get this added to webp, the most bandwidth-friendly image format, and you’re halfway there.

  14. It’s great to read something that doesn’t just highlight problems, but actually proposes a workable solution. Hopefully the W3C take note.

    Re your current problem of mobile image appearing before the full sized. What about sizing the mobile image using it’s “intrinsic ratio”: , and then front loading the full size over the top, so it effectively becomes more detailed rather than changing size.

    Wouldn’t fix the bandwidth issue, but could be less jumpy!

    Thanks the the article, great read!

  15. I arrived at the same conclusion. In my own frustrating attempts at mobile-first-avoid-redundant-downloads-design, I concluded that I needed a video-like element with multiple src elements, as well. I implemented the design using divs and allowed JavaScript to dynamically swap out images based on window dimensions. It works, but I would certainly welcome an official W3C construct.

  16. Hey folks, just want to stress that I wasn’t proposing anything in the way of bandwidth detection—just pointing out that a huge bandwidth hit is what we’re looking to avoid, and we do so by ensuring that we’re not serving an image any larger than the user could need. Media attributes on sources could potentially mean a bandwidth-specific solution, but I’d think something like that would best be used to serve up images of varied compression rather than images of various sizes. Screen size directly relates to the problem we’re looking to solve.

    *tesmond*: It sounds like you’re looking for a separate solution altogether, for images that are _intended_ to be larger than the users’ displays. In that case, a solution like you propose may be the right one: downloading the image in tiles. Keep in mind that our proposal is by no means a replacement for the img tag—it’s just one solution to a specific issue.

  17. i love the picture tag idea with multiple sources. I’m not sure “picture” is the right word, i always think of photograph, landscape etc when hearing that word. Not applicable for a logo.
    the problem i’ve had with responsive design on this note is that we got away from separating design and content when CSS really took off. Now, to make sites responsive we’re back tracking a little by placing images in the mark up again when they could be background images.
    that said, its not the end of the world.

    If however we’re going to go this far, by having a new “picture” tag, and multiple sources. It would be nice to go the extra mile by taking a que from style tags. Meaning, a version of media=”screen” for the source tags. Shouldn’t be too much to ask I dont think. If a new tag has to be adopted might as well go the distance. media=”small”, media=”medium”, media=”large”, media=”xsmall”, media=”xlarge” etc etc.

    If the goal is to load images based on screen size for the sake of loading speed, why not make the job easier on ourselves by being able to force certain ones to load at certain times, and bypassing the rest.

    Those are my thoughts.

    I’ll be at An Event Apart ATL. Looking forward to all the responsive discussions!

  18. A long, long time ago the “lowsrc”: attribute would handle something very similar to this. It would be nice to have it back again to quickly load an image on any browser, then once everything is in place start working on high res if possible. A non-js implementation would be ideal, as you wrote towards the end of your post better fallbacks and conditional loading would be wonderful. Some other options for responsive loading were discussed on “quirksmode”: ,

  19. I think this idea of a element.

    One thing that caught my eye was the repeated idea of:

    Wouldn’t it be nicer to simply use as the standard image so you only need to declare it once and add alternative images?


  20. This design pattern should be broken out for all media really:

    <video src=”high-res.webm” media=”min-width:800px” />
    <video src=”low-res.webm” />

  21. has been a closed tag forever, why not just allow the tag to be opened and use a format like.

    No new tag, older content still works, and we get real responsive images.

  22. I’ve looked at it in a similar way to @steveu in comment 17. I’ve experimented with loading the small image for all browsers (sized _up_ if necessary) and replacing it with the larger image via javascript as needed. As you mention, in high-bandwidth situations users get a flash of the blurry image, which resolves very quickly to the high-res image if the bandwidth is decent. It’s maybe not the _most_ ideal (I like the new markup proposal) but it works adequately in every case.

    In my mind, this approach has the added advantage of a super-fast initial display for everyone (including desktops), since they only have to download the teeny images at first. From what I’ve seen, many people will be okay with a progressive image load if it makes the site faster.

  23. It is becoming clear to me that “responsive” design leaves all layout choices in the hands of the designers (where it should be) and “adaptive” requires more consultation with the developers, and the best result will probably be a combination of them. I would like to see the web change to offering as much control over layout and content to the front end developers as possible, but we’re not there yet.

    For a simple page that only contains content you want to display anywhere, if the images can be delivered as CSS background images then surely @media queries would be way to go, specifying a different image depending on screen size.

    If the design has been created in that quaint, print-focussed, Photoshop-a desktop-design-first approach, then a mobile site may have to be assembled with a controller selecting a different set of models and views depending on the user agent.

    Right now I’m advocating adaptive techniques as a fall back, and they are often the only way to effectively “mobilize” an old-fashioned web site reasonably quickly. The benefit of this is that the client will soon want their desktop site to be as efficient and user-friendly as the mobile version.

    Keep the pressure

  24. Certainly the news is only grim for client-side approaches. For those of us with CMSes or access to php, the outlook has to be more positive.

  25. I’d strongly encourage everyone to read “Jason Grigg’s article on responsive images”: (which Mat linked to.)

    It explains a lot of the difficulties that you have to work around in order to develop a responsive image solution. By far the worst one is the “First page load problem”. If you want to use JavaScript to determine the capabilities of the user’s browser, you can’t do that _before_ you send your first page’s content. And you can’t try to use some blocking JS in the <head> that determines capabilities before the body is parsed”¦ because of the new techniques Mat mentioned where they pre-fetch images before building up the DOM of the body. And you can’t use data-URIs and “blank images” because “a with no src is not actually blank”: .

    Which means on the first connection, you don’t know anything about the browser, so you can’t send “the right image” to it. If you want to try to figure out some of the capabilities of the browser before you send the first page of data, you have to rely on UA sniffing. UA sniffing is fragile and requires constant updating of your UA database.

    So, yes, you can build server-side solutions into a CMS, but that UA-sniffing code will never be as robust as a native HTML solution could be. Personally, I’d like to try to build a server-side solution that uses a Future Friendly markup with the element.

  26. *DavidSparks*: Yeah, I’m not 100% married to “picture,” to represent the new element. “Poster” would make more sense, but it’s a term already in use and that might trip people up. Maybe “art?” Stuff we can nail down once we have something working, I figure.

    In terms of the media attributes, you could still specify media=”screen” and the like in there—you can use any combination of media queries, the same as you would in your CSS. I like it because it paves the way for exactly the kind of conversation you’re mentioning: as media queries change and adapt over time, so too can this new element.

    And the best part is that the HTML5 dictates that sources that don’t match the media attribute are never requested. If implemented correctly, it does exactly what you’ve said: grab the source we want, and bypass all the rest.

  27. bq. Some of our first iterations involved

    What problems did you find while using the

    I made a script for using the noscript tag technique without any pain. It is small and fast, but yet flexible. Please give it a spin:

    The good part is that it involves no backend nor cookies *and* it works just perfect without JavaScript enabled.

    Anyway, let’s hope that browsers will implement a clean solution for this any time soon.

  28. Fantastic work on a tricky problem. I agree that JS should not handle img sizing and server side tricks are just not applicable, I can imagine many situations where server side programmers are gonna get well pissed with front end guys requesting, new and different solutions. However, I believe CSS to be the route that should be used, after all CSS is presentational whilst mark-up describes content and in this context I would regard imgs as presentational.

  29. *frederfred*: Clever stuff, man! I’m not gonna lie: as frustrating as the responsive images problem has been at times, it has given way to some truly brilliant hacks. It ain’t always pretty (see also: some of our attempts at swapping <video> posters on-the-fly), but it leads to some wildly creative approaches.

    Though, as Scott Jehl once said of a particularly desperate brainstorming session: “if this conversation gets leaked to the press, we’re both going to web standards hell.”

  30. What about the <object> tag? I have to admit, I’ve never used <object> to post an image, and I’ve only had other programs generate its sloppy markup for me. But displaying images is one of its purposes, as listed in the spec. It also has a built-in and well-documented fallback.

    I wonder if something like that could work.

  31. What about using a user agent query in the htaccess instead of the cookie. Basically redirect image requests for only mobile browsers. Now I know using User Agent Strings to detect something like an iPhone isn’t best way to do it, because User Agents can be spoofed but realistically aren’t those edge cases, like ie5 visits 🙂

  32. There is also another problem related with images. Lazy loading. With HTML5 we got async attribute to script element but no way to postpone image loading, force client to wait until image is really needed. For example imagine CSS3 based carousel with 10, 100 KB each sized images. We need to fallback to JS code to inject images to the page. In my opinion there should be something like , when visible browser should request it and then apply all css rules (including effects, like transitions).

  33. *thezenmonkey*: That’s possible, for certain—though, as you mention, we’d be opening ourselves up to various the issues that UA-detection entails. Spoofing, for one thing, and managing a growing and evolving list of devices for another. It becomes a bit more reasonable knowing we’d likely default to a smaller image and send the full-size image down the pipe only if a desktop UA string is matched (as we always want to fail in a way that’s still beneficial to users), but it still feels more like a stopgap solution to me.

  34. Personally I love the approach being presented in the article. I have often found that many developers over-complicate solutions when something could be just as simple as a picture tag.

    It would be nice to find a solution for responsive images that really works and is accepted cross browser.

    Even if something like this were to be come standard, how long would it be till most browsers were implementing it?

  35. Mat’s essay mentions that the work-around hacks by his team and others fails when ‘newer’ (and unmentioned) browsers may, upon parsing a link or via markup, proactively download things.

    Work-arounds that rely on cookies and/or script-replacement may see issues, as the Boston Globe does now.

    A semantic note: a pre-_fetch_ is, at present, a request to pre-load resources, on an individual basis. One HTML file, one image, etc. I do not believe any browsers parse said HTML and load its referenced resources when in this mode. A pre-_render_, on the other hand, loads a page and all its content, but keeps it hidden. At the moment, “it only happens on Chrome”: . These are different from a _DNS_-pre-fetch, which simply resolves IP addresses for faster browser-to-server first-contact.

    When Firefox pre-fetches content (at the behest of the referrer page’s markup), it sends the following header with the request: @X-moz: prefetch@

    Safari does similarly, using: @X-Purpose: preview@. According to “this ticket”: , Chrome does, too.

    For pre-rendering, Chrome does not send any header whatsoever to the client. Instead, one must use the “Page Visibility API”:, in JS.

    *What to do*

    In most circumstances, a pre-fetch ought not to be initiated on a mobile browser without a lot of forethought. If you think said mobile browsers will hold to that idea (and I hope you’re right), you can watch for the HTTP pre-fetch headers, and make sure to load the full-size image for that request.

    The various browsers need to be lobbied for an opt-out, too. While at the time, I thought the “effectively-mandated”: IE-8 @X-UA-Compatible@ header was horrendous, at least it put the capacity for control in the hands of an individual site. As browser-makers add whiz-bang features to their products, we as site builders need mechanisms to deliberately opt-out of those that would negatively affect user experience.

    The DNS-prefetch implementors did this right. The @X-DNS-Prefetch-Control@ header allows a site-owner to opt-out gracefully.

  36. Remember the early days of the web, watching interlaced GIFs load, bit by bit, as though looking through a window whose blinds were being slowly opened? No? Get off my lawn.

    Through a different methods, progressive image loading is supported by PNG and JPEG, as well. I don’t see anything regarding the new kid, WebP.

    Imagine, for a moment, a single image file that would look correct on browsers of any size and connectivity. In theory, this is possible when interlaced images are handled properly.

    A 800x800px image has four times as many pixels as its imaginary mobile-sized counterpart, which clocks in at 400x400px. Now imagine this larger image is a progressive image. In order to display this image well at the smaller, mobile size, *one could theoretically load only one-quarter of the original image*.

    (Yes, I know there are overheads to progressive images. An image file, when saved progressively, is usually slightly larger than a non-progressive file. _”There can be no progress, no achievement without sacrifice…”_ -James Allen)

    That sounds like a good future, doesn’t it? Because the browser understands the rendering intention (size), it can load only as much of the image as it needs to display it well. A _really_ intelligent browser would consider this a partial download, and remember the file offset in case it wanted an even bigger image and decided to resume download.

    The best of all worlds, without new markup.

    Now if only _someone_ would support JPEG2000, which is supposed to do an even better job at interlacing.

  37. *wessman*: Oh dude, that is some _serious_ knowledge you’ve just dropped. It’s very possible this means our original responsive images script is _still viable_. Granted it’s still a workaround for a pretty fundamental issue—and in no way changes my upcoming letter to Santa/the WHATWG—but this is absolute gold.

    If you should ever find yourself in Boston, sir, I owe you a beer.

  38. It seems to me that any technique that requires web developers to implement additional complex markup is only ever going to have a low takeup. If a device can only render a low res image it should probably make that clear in the headers of its request, and then web servers can scale images before sending them. This kind of approach can be implemented transparently and would work with existing sites and markup.

  39. Detective work is not an easy thing to accomplish, but the image element replaced with an audio/video like approach is brilliant. Not only do we need to detect for resolution/screen size for imagery, but also scripts and libraries that are not needed for certain devices.

    The Filament Group implemented EnhanceJS which is brilliant and totally useful for detection, but as of today there isn’t a ton of interest on their google code page. Also currently Modernizr also wont detect the max-device-width media query for its load property.

    Too bad these options and solutions are not bringing in attraction as we seemed to be concerned with image sizes rather than the whole ball of wax. Thanks for the deep thoughts and share :)p

  40. Hey Mat, really good article on image options for mobile first development. I was very curious on how we, as designers and developers, could get in on the conversations with WHATWG and the like about implementing better options for images in HTML markup.

    Is there an easy way to join the conversation and would it be helpful to have more people in on it?


  41. Guys, thank you very much for all the feedback! This is the only way to get this topic in the right direction and to get a working code.

    As a result I’ve spend some hours reading, analyzing the comments and sorted out. This is what is valuable feedback (sorry, I sorted out all the duplicates of code-element-names etc.): “See my updated article”:

    @Mat: What do you plan on the WHATWG list? I’d recommend moving the topic forward in W3C’s “public-html”-list where the topic is already in list here: “[whatwg] add html-attribute for responsive images”:
    So please don’t open up a new duplicate while another topic has already run through the WHATWG lists and moved to W3C’s list. Thanks!
    If you have questions, please don’t hesitate to contact me.


  42. I haven’t read all of the responses here but I’ve been thinking over this. I would love to see a ‘path’ option that could be included as part of the CSS and be a distinction in the media query. So for a normal 960 or larger view you could have img path:fullsize; and that could switch for tablets and mobile depending on the media query to be path:tablet; or path:mobile; as needed which would pull the appropriate image source from the folder that is being called. It is a bit of work easily solved through resizing actions. Much less work than what is currently needed with video and the various formats that are needed to degrade properly.

  43. @my ad: As far as I understood you’re talking about a solution to solve the responsive image problem inside CSS, too. This is something you can read in my proposal here: “see blog article”:
    I like the idea of being responsive in either way — informational elements in HTML, non-informational/styling-elements in CSS.

    Is that what you’ve been thinking of? If not, please clarify so we can sort this out.

  44. @anselmh Yes, I would like to see the solution come through CSS as I think it is the best way to approach it for the long term. Adding in javascript workarounds seems messy to me as we look into the future and think it only serves as a crutch to the bigger issues.

    Thinking this through over the morning I’ve found various issues with my original thought and what could be solutions or could lead to complications. Below is a breakdown of how it could work changing around how a few things are currently structured.

    Through the img tag you would nolonger specify an full path to the asset as it is currently structured. ie, img src=”folder/logo.jpg”

    This would be handled through the CSS file using ‘path’ or some other specifier. So the document would now look as follows.


    img src=”logo.jpg”


    img { path: desktop; }

    This would lead the logo.jpg to be pulled from an image folder named ‘desktop’ and retrieve the full size asset.

    This can be changed using media queries to pull the different size assets from a different source folder as follows.

    @media screen and (max-width: 480px) {
    img { path: mobile; }

    If a person doesn’t like to have all images coming out of one directory you could pull images out of various folders through a class element. { path: company; }
    img.products { path: products; }

    resulting in – img class”company” src=”logo.jpg”

    and so on.

    You could specify where the assets are coming from depending on the different scenarios that are being designed for. As we look ahead screen sizes and resolutions are going to keep multiplying and we’ll very soon be taking into account televisions adding more complexities.

    Using this approach front end devs that are not concerned with responsive design can still use the traditional path structure without specifying path: ; in the CSS – img src=”folder/logo.jpg” and it would work as expected.

    The part that I’m not fond about is having to create various sizes of the same image however this also opens up a number of design opportunities as you can customize images depending on which display it is being viewed on.

    I see this providing designers a lot of potential to customize how a page would look and deliver images to that specific device instead of needing to use the same image for every instance and simply scaling it.

    This approach keeps the current responsive principles and allows for additional customization but my favorite part of this solution is it only adds one piece of code and leaves the rest of the styled elements via CSS as is.

  45. I should clarify when I say ‘I would like to see the solution come through CSS’. Ideally the best solution would be native HTML enhanced by CSS. The HTML would be a fall back to an enhanced CSS solution.

  46. I still think that that there should be an all emcompassing tag that would allow the browser to gracefully degrade from <video> to to any other element you could use for that area (and dependent on a standard media attribute). It seems like the video tag is only scratching the surface of the power of graceful degradation via HTML, why stop there? What about using a shorter headline or paragraph text if the viewport is smaller? Why not give us the option of giving a html alternative for an image versus relying on basic text in an alt tag?

    Too many tags, not enough scalability.

  47. As our mobile-large screen responsive evolution presses on at warp speed… those on the crest of the wave are held back by seemingly simple technological hurdles. We have to remember the large screen in the equation as brand channels will begin to immerge with one feed -> mobile-large screen.

    Our frustrations are but a small slice in time. What may seem like a solution today, may be an obstacle in only a matter of months.

    I so love your suggested solution. It absolutely makes sense – today… and is evolution enabled.

    Well said and good luck in persuading the powers that be to enable these markup improvements.

    Responsive image nirvana.

  48. This is excellent article in the way it expresses what developers go through in battling how things change and evolve on the web and whereby most designers don’t ever really get the intricacies that developers have to deal with.

    I think it’s not enough for designers to just study design, they need to study structure and code as well. The reverse is equally important but I think there’s plenty of momentum lately for developers to understand the importance of great design. Full disclosure, as a former developer, I may be biased in who I think needs to work harder. 🙂 Nevertheless, nice article!

  49. All these approaches put to much of a burden on developers! They’re clunky, prone to breakage and force the use of more markup. But maybe worst of all they force you to define fixed dimensions where you switch the image and to maintain multiple versions of the image!
    I’m really quite astonished that no one so far has mentioned that JPEG 2000 together with the JPIP protocol handles this use case already… Store the image on the server in the maximum resolution you want to offer, but just download a size appropriate for the user’s display. Open source JPIP servers are available… (Djatoka for instance can serve ‘regular’ formats from a jp2 file, providing a fallback.) Better native support for JPEG 2000 in browsers would be nice of course.

    Some experiments need to be done on how best to use inline JPEG 2000 for responsive images. I suppose one approach could be sending a scaling factor (or max size) with a cookie and do some URI rewriting on the server side to get the desired image size. CSS can still be used to downscale the image for a perfect fit. It’s not optimal, but the main point is to just work with one image and let the server handle the scaling.

    Yes, JPEG 2000 requires encoders/decoders that are complex and more computationally ‘demanding’. But there has to be a tradeoff somewhere.

    And let’s not forget that JPEG 2000 offers many other useful features.

  50. I wrote the comment above in a hurry and forgot to clarify that of course no browser currently implements the JPIP protocol. However I still think using a JPEG 2000 server over HTTP could be a very interesting method towards solving the problem of responsive images. And it would certainly help push native implementations of the JPEG 2000 standard.

  51. What about an approach of using the CSS media type to control the image source? No JavaScript involved, but it does assume that mobile devices come up with a media type of handheld. You probably can’t use the img tag, but maybe a div tag. Then again it changes the function of the div tag and is not semantically correct. A change to the markup to support images like videos would still be the best option.

  52. I’ve been experimenting with this, . I watched the resources as I expanded the window and the different image for the widest display isn’t requested until that CSS is triggered by the window reaching each specified width. (I cused different images so I could see the change easily).

    No Javascript at all.



    @media screen and (orientation:landscape) and (min-width:480px){


    @media screen and (orientation:landscape) and (min-width:1024px){


  53. I agree, a picture tag was perfect to solve this problem, we have a solution for this, but this solution is not easy to implement, and, at this time, we have to care about many device sizes more and more. Hey W3C, look this post! 😛

  54. @Marc Diethelm: This is entirely the best solution. I’ve written about it as the “perfect solution” in my blog post. The problem is, that JPEG2000 isn’t that good of a format for graphics. So we would need ideally WebP/WebM to be able to progressively download and serve responsive images. Until that is implemented in all browsers (haha!) you will still need another approach, so that’s why we proposed the HTML5 solution for interim.

    @JCOELHO, @yeosteve: A CSS only solution wouldn’t work as it’s not semantic and doesn’t work valid. It still should be possible to do via CSS for non-semantic (styling/layout) purposes, too. Mailing list of W3C didn’t care about this very much 😉

    @Anserson Schmitt: We (Mat and I) are currently discussing on WHATWG lists and if we have a solution over there, it will move to the W3C list. So be sure we do our best W3C cares about this problem 🙂

    @ NatCk: is only a polyfill solution and uses some technique not very good for a standard-solution.

  55. Since we’re talking about changing the browser’s behavior anyway, why not actually make it offer up the information to properly solve this problem server-side? Let’s have the browser send the information that is available to the “css media queries”: in the HTTP GET request headers caused by the one-and-only tag or CSS url(“whatever.png”).

    To wit:
    X-Media: “screen color:24 resolution:120dpi orientation:portrait device:640×480 viewport:500×300”

    (obviously, the aspect-ratio and device-aspect-ratio can be computed, color-index seems meh)

    The nice thing about this is that it is really up to the user-agent’s current needs to determine what should be displayed, thus what should be requested. If someone zooms in, the user-agent can ask for a bigger version. If they switch to print view, we can ask for the monochrome version in higher DPI and all is warm and fuzzy. If the server doesn’t care, it serves up the one-true-image. If the server cares, it can serve specific versions. Cache logic can be driven by the standard content-negotiation logic (and left non-cached until it is).

    The best part of ALL of this is that the CSS can just reference an image, the html can just include a img tag, etc… and the browser’s request can be driven by what it knows already about the size/placement/device of the image.

  56. Use JavaScript stylesheet manipulation. All responsive images should be rendered in an with a token classname, such as ‘responsive’, and should have fallback ‘src’ value. In <head>, JS will add a stylesheet rule to ‘display:none’ all such elements (to avoid requesting the wrong image resource), then will determine the appropriate screen size category. Script block at the bottom of the page will alter ‘src’ values of all responsive s according to screen size category, per some naming convention, and then update stylesheet rule to ‘display:inline’ all such elements.

    This may cause flicker, more noticeable when HTML is generated/delivered slowly. This can be mitigated by encapsulating the responsive in some server-side component that also emits a script block right after each to do the ‘src’ attribute manipulation and displaying.

    The ‘resize’ event will be handled to perform this logic in case different images need to be re-rendered (can be short-circuited if new image would have lower quality).

    If UA doesn’t support JS or doesn’t support stylesheet manipulation, there will be flicker or simply the fallback content is rendered.

  57. Is there a reason why you can’t just use images as the source in the video tag with the image MIME type, as in the following example??



  58. The “Responsive Content”: jQuery plugin is an approach which works in a “coarse grained” way, ajax-loading an entire HTML fragment into the page, given current window width (and pixel density). It can be used to tell the server to supply appropriately sized image src URLs etc.

    It’s a fork of Github’s Pjax loader. It does not rely on User Agent or cookies – just window width.

  59. How do would you appreciate these 2 solutions to download only the small images when needed (Smartphone, iPhone, Android)
    1) Use $_SERVER(‘HTTP_USER_AGENT’) in the server script to detect that it is not a PC
    2) Have a main page that detects the screen size and pass it in the URI for subsequent pages.

  60. A great solution to <video>-like functionality. Wondering if a similar functionality can make element accept multiple sources like video does.

Got something to say?

We have turned off comments, but you can see what folks had to say before we did so.

More from ALA