HTTP Client Hints
The Client Hints (CH) header communicates device capabilities to the server, allowing the server to return the best possible experience back to the device.
This project aims to polyfill CH to the best abilities of the device and server.
How it works:
One line of JavaScript can make a variety of hints available to the server. For instance, if the following script is included at the top of the document, all future requests (even those made from that same document) can leverage these hints. The draft calls for 3 hints; device pixel ratio, device width, and device height.
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=/';
Or as separated hints.
(function (p, e, k) {
for (k in p) document.cookie = 'CH-' + k + '=' + p[k] + e;
})({
DH: screen.height,
DW: screen.width,
DPR: window.devicePixelRatio || 1,
T: 'ontouchstart' in window || 'msMaxTouchPoints' in navigator
}, ';expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/');
Since these 3 CH are unlikely to change in a given session, the above snippet could be wrapped in a server-side conditional to load just once.
<?php if (!isset($_SERVER['HTTP_CH'])) : ?>
<script>document.cookie = ...</script>
<?php endIf; ?>
The native implementation of CH works by sending hints through a request header, which the server could cache. This polyfill emulates the projected end-result — a server with a cache of hints.
What is included:
create.htaccess
An Apache configuration snippet for converting a CH cookie into a server environment variable.
create.js
A JavaScript snippet for creating a CH cookie.
create.php
A PHP snippet for conditionally creating a CH cookie when the server environment variable is not yet found.
What the future holds:
An issue on GitHub suggests including more dynamic data in CH, such as device orientation, viewport size, and zoom level as well.
Admittedly, these values change frequently and are difficult to cache
, whereas the currently drafted hints are unlikely to change in the life of the device.
Since CH adoption is in its early stages, Ilya Grigorik, author of the HTTP Client Hints Draft, argues that the CH header must be kept as small and as static as possible to prove its viability
.
Native implementation status:
All of these contributions to CH are dedicated to the public domain with no copyright.