FetchEvent: preloadResponse property

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

Note: This feature is only available in Service Workers.

The preloadResponse read-only property of the FetchEvent interface returns a Promise that resolves to the navigation preload Response if navigation preload was triggered, or undefined otherwise.

Navigation preload is triggered if navigation preload is enabled, the request is a GET request, and the request is a navigation request (generated by the browser when loading pages and iframes).

A service worker can wait on this promise in its fetch event handler in order to track completion of a fetch request made during service-worker boot.

Value

A Promise that resolves to a Response or otherwise to undefined.

Examples

This code snippet is from Speed up Service Worker with Navigation Preloads.

The onfetch event handler listens for the fetch event. When fired, the handler calls FetchEvent.respondWith() to pass a promise back to the controlled page. This promise will resolve with the requested resource.

If there is a matching URL request in the Cache object, then the code returns a promise for fetching the response from the cache. If no match is found in the cache, the code returns the promise in preloadResponse. If there is no matching cache or preloaded response, the code fetches the response from the network and returns the associated promise.

js
addEventListener("fetch", (event) => {
  event.respondWith(
    (async () => {
      // Respond from the cache if we can
      const cachedResponse = await caches.match(event.request);
      if (cachedResponse) return cachedResponse;

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

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

Specifications

Specification
Service Workers
# fetch-event-preloadresponse

Browser compatibility

BCD tables only load in the browser

See also