Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created October 23, 2015 14:52
Show Gist options
  • Save deanhume/52c4c4f7f07c2e1d7db7 to your computer and use it in GitHub Desktop.
Save deanhume/52c4c4f7f07c2e1d7db7 to your computer and use it in GitHub Desktop.
Dynamic Responsive images using Client Hints and Service Worker
// Listen to fetch events
self.addEventListener('fetch', function(event) {
// Clone the request
var req = event.request.clone();
// Check if the image is a jpeg
if (/\.jpg$/.test(event.request.url)) {
// Check the headers
for (entry of req.headers.entries()) {
// Check the accept header
if (entry[0] == 'accept')
{
if (entry[1].includes('webp'))
{
// change the return path
var returnUrl = req.url.substr(0, req.url.lastIndexOf(".")) + ".webp";
event.respondWith(
fetch(returnUrl, {
mode: 'no-cors'
})
);
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment