MattWilcox/Adaptive-Images — pull request #128 by ebollens (2013-10-09 04:42:29+00:00)
Title: Fallback to HTTP Client Hints

The [HTTP Client Hints](http://tools.ietf.org/html/draft-grigorik-http-client-hints-00) draft specification (IETF Network Working Group) proposes a new CH request header field for the HTTP protocol that includes three attributes in its core definition:

* `dh` for the device-width in secondary orientation
* `dw` for the device-width in primary orientation
* `dpr` as the ratio between physical pixels and density-independent pixels on the device.

As should be apparent, these are exactly the same values we need for Adaptive Images.

To quote the abstract:

> An increasing diversity of connected device form factors and software capabilities has created a need to deliver varying, or optimized content for each device.
>
> Client Hints can be used as input to proactive content negotiation; just as the Accept header allowed clients to indicate what formats they prefer, Client Hints allow clients to indicate a list of device and agent specific preferences.

Ilya Grigorik, developer advocate at Google who's also the principal here, did a [good post on his blog about it](http://www.igvita.com/2013/08/29/automating-dpr-switching-with-client-hints/), and [it was just added to the latest build of Chromium](https://plus.google.com/100132233764003563318/posts/AS432bKs7pY) with the `--enable-client-hints` switch.

Clearly, it's not quite there yet, but there's a [cookie-based polyfill available](https://github.com/jonathantneal/http-client-hints) that already it possible. At its core, it's just a one-liner:

```js
document.cookie="CH=dh="+screen.height+",dpr="+(window.devicePixelRatio||1)+",dw="+screen.width+",t"+("ontouchstart"in window||"msMaxTouchPoints"in navigator)+";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/";
```

In addition, an `.htaccess` file is provided that exposes this like an HTTP header:

```
# Get the client hints cookie
RewriteCond %{HTTP_COOKIE} CH=([^;]+)

# Set the client hints header
RewriteRule .* - [E=HTTP_CH:%1]
```

In working with some apps that are already using this, and in thinking about the future, I'm submitting a pull request that does the minimal amount of legwork to add support for HTTP Client Hints *as a fallback* in the event that the `resolution` cookie is not set. The benefits: (1) if someone is already using HTTP Client Hints, they will be able to leverage Adaptive Images without any changes, and (2) it looks to the future for when *hopefully* this is implemented in all major browsers.

PS. In doing the "minimal amount of legwork to add support", there might be some polishing to be done to get it in a style preferable to the maintainer - but this is meant to start the conversation (and hopefully to be useful, of course).