SHARE
TWEET

Untitled

a guest Mar 25th, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. addEventListener('fetch', event => {
  2.    event.respondWith(makeWebp(event.request))
  3. })
  4.  
  5. async function makeWebp(request) {
  6.    let regex = /\.jpg$|\.jpeg$|\.png$/i
  7.    if(request.headers.get('Accept')
  8.        && request.headers.get('Accept').match(/image\/webp/)
  9.        && request.url.match(regex)
  10.        && !request.url.includes('/original/')) {
  11.        /**
  12.         * Replace jpg / png with webp
  13.         */
  14.        let url = new URL(request.url.replace(regex, '.webp'))
  15.  
  16.        /**
  17.         * Create a new request with the webp url
  18.         */
  19.        const modifiedRequest = new Request(url, {
  20.            method: request.method,
  21.            headers: request.headers
  22.        })
  23.  
  24.        /**
  25.         * Fetch the webp response
  26.         */
  27.        const webpResponse = await fetch(modifiedRequest)
  28.  
  29.        /**
  30.         * Add webworker header to the webp response so we can
  31.         * check live if the webworking is doing what it should do
  32.         */
  33.        const webpHeaders = new Headers(webpResponse.headers)
  34.        webpHeaders.set('Content-Type', 'image/webp')
  35.        webpHeaders.append('X-WebWorker', 'active')
  36.  
  37.        /**
  38.         * Return a new response object
  39.         */
  40.        return new Response(webpResponse.body, {
  41.            status: webpResponse.status,
  42.            statusText: webpResponse.statusText,
  43.            headers: webpHeaders
  44.        })
  45.  
  46.    } else {
  47.        const response = await fetch(request)
  48.        return response
  49.    }
  50. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top