Skip to content

Instantly share code, notes, and snippets.

@deanhume
Last active September 10, 2017 11:03
Show Gist options
  • Save deanhume/c04478df744ce833925c to your computer and use it in GitHub Desktop.
Save deanhume/c04478df744ce833925c to your computer and use it in GitHub Desktop.
Service Worker & HTTP Client Hints
"use strict";
// Listen to fetch events
self.addEventListener('fetch', function(event) {
// Check if the image is a jpeg
if (/\.jpg$|.png$/.test(event.request.url)) {
// Inspect the accept header for WebP support
var supportsWebp = false;
if (event.request.headers.has('accept')){
supportsWebp = event.request.headers
.get('accept')
.includes('webp');
}
// If we support WebP
if (supportsWebp)
{
// Clone the request
var req = event.request.clone();
// Build the return URL
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