FetchEvent: preloadResponse property - Web APIs | MDN
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 Nightly # fetch-event-preloadresponse |