Last active
September 10, 2017 11:03
-
-
Save deanhume/c04478df744ce833925c to your computer and use it in GitHub Desktop.
Service Worker & HTTP Client Hints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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