docs.rodeo

MDN Web Docs mirror

FetchEvent

{{APIRef("Service Workers API")}} {{AvailableInWorkers("service")}} 

This is the event type for fetch events dispatched on the {{domxref("ServiceWorkerGlobalScope", "service worker global scope", "", 1)}} . It contains information about the fetch, including the request and how the receiver will treat the response. It provides the {{domxref("FetchEvent.respondWith", "event.respondWith()")}}  method, which allows us to provide a response to this fetch.

{{InheritanceDiagram}} 

Constructor

Instance properties

Inherits properties from its ancestor, {{domxref("Event")}} .

Instance methods

Inherits methods from its parent, {{domxref("ExtendableEvent")}} .

Examples

This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time.

self.addEventListener("fetch", (event) => {
  // Let the browser do its default thing
  // for non-GET requests.
  if (event.request.method !== "GET") return;

  // Prevent the default, and handle the request ourselves.
  event.respondWith(
    (async () => {
      // Try to get the response from a cache.
      const cache = await caches.open("dynamic-v1");
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // If we found a match in the cache, return it, but also
        // update the entry in the cache in the background.
        event.waitUntil(cache.add(event.request));
        return cachedResponse;
      }

      // If we didn't find a match in the cache, use the network.
      return fetch(event.request);
    })(),
  );
});

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN