MDN self-hosted library · e01.org

FetchEvent: preloadResponse property

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
addEventListener("fetch", (event) => {
  event.respondWith(
    (async () => {
      const preloadResponsePromise = event.preloadResponse;

      // Respond from the cache if we can
      const cachedResponse = await caches.match(event.request);
      if (cachedResponse) {
        // Keep the navigation preload request alive even if we do not use its response.
        event.waitUntil(preloadResponsePromise.catch(() => undefined));
        return cachedResponse;
      }

      // Else, use the preloaded response, if it's there
      const response = await preloadResponsePromise;
      if (response) return response;

      // Else try the network.
      return fetch(event.request);
    })(),
  );
});