-
-
Save snowman-repos/8ab75338861678e45269 to your computer and use it in GitHub Desktop.
Service Worker & HTTP Client Hints
This file contains hidden or 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