Created
October 23, 2015 14:52
-
-
Save deanhume/52c4c4f7f07c2e1d7db7 to your computer and use it in GitHub Desktop.
Dynamic Responsive images using Client Hints and Service Worker
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
// 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