Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- addEventListener('fetch', event => {
- event.respondWith(makeWebp(event.request))
- })
- async function makeWebp(request) {
- let regex = /\.jpg$|\.jpeg$|\.png$/i
- if(request.headers.get('Accept')
- && request.headers.get('Accept').match(/image\/webp/)
- && request.url.match(regex)
- && !request.url.includes('/original/')) {
- /**
- * Replace jpg / png with webp
- */
- let url = new URL(request.url.replace(regex, '.webp'))
- /**
- * Create a new request with the webp url
- */
- const modifiedRequest = new Request(url, {
- method: request.method,
- headers: request.headers
- })
- /**
- * Fetch the webp response
- */
- const webpResponse = await fetch(modifiedRequest)
- /**
- * Add webworker header to the webp response so we can
- * check live if the webworking is doing what it should do
- */
- const webpHeaders = new Headers(webpResponse.headers)
- webpHeaders.set('Content-Type', 'image/webp')
- webpHeaders.append('X-WebWorker', 'active')
- /**
- * Return a new response object
- */
- return new Response(webpResponse.body, {
- status: webpResponse.status,
- statusText: webpResponse.statusText,
- headers: webpHeaders
- })
- } else {
- const response = await fetch(request)
- return response
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement