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.
A Promise
that resolves to a Response
or otherwise to undefined
.
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.
addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
const cachedResponse = await caches.match(event.request);
if (cachedResponse) return cachedResponse;
const response = await event.preloadResponse;
if (response) return response;
return fetch(event.request);
})(),
);
});