Fetching with service workers

Once everything is ready, you should be able to intercept requests with your service workers with the fetch event, in the following way:

self.addEventListener('fetch', e => {    e.respondWith(async function() {        const response = await caches.match(e.request);        if(response) {            return response;        }        return fetch(e.request);  }());});

Hang on! Let's see what happened here:

  1. This listener will be fired whenever the browser makes a fetch request under its registration scope (we discussed that earlier).
  2. respondWith also accepts a promise, which we gave it.
  3. Then, we check whether or not the requested file is already present in our cache (using catches.match(e.request)). If it is, we return the cached file directly. If not, we ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.