W3cubDocs

/Web APIs

FetchEvent: preloadResponse property

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

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
preloadResponse 59 18 99 No 46 15.4 59 59 99 43 15.4 7.0

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/preloadResponse