Navigation preloads in service workers

Jeremy Keith
Aug 1 · 5 min read
if (registration.navigationPreload) {
addEventListener('activate', activateEvent => {
activateEvent.waitUntil(
registration.navigationPreload.enable()
);
});
}
addEventListener('fetch', fetchEvent => {
const request = fetchEvent.request;
if (request.headers.get('Accept').includes('text/html')) {
fetchEvent.respondWith(
fetch(request)
.then( responseFromFetch => {
// maybe cache this response for later here.
return responseFromFetch;
})
.catch( fetchError => {
return caches.match(request)
.then( responseFromCache => {
return responseFromCache || caches.match('/offline');
});
});
);
}
});
fetchEvent.preloadResponse
if (fetchEvent.preloadResponse) {
// do something with fetchEvent.preloadResponse
} else {
// do something with fetch(request)
}
addEventListener('fetch', fetchEvent => {
const request = fetchEvent.request;
if (request.headers.get('Accept').includes('text/html')) {
fetchEvent.respondWith(
if (fetchEvent.preloadResponse) {
fetchEvent.preloadResponse
.then( responseFromPreload => {
// maybe cache this response for later here.
return responseFromPreload;
})
.catch( preloadError => {
return caches.match(request)
.then( responseFromCache => {
return responseFromCache || caches.match('/offline');
});
});
);
} else {
fetchEvent.respondWith(
fetch(request)
.then( responseFromFetch => {
// maybe cache this response for later here.
return responseFromFetch;
})
.catch( fetchError => {
return caches.match(request)
.then( responseFromCache => {
return responseFromCache || caches.match('/offline');
});
});
);
}
});
let retrieve;
if (fetchEvent.preloadResponse) {
retrieve = fetchEvent.preloadResponse;
}
let retrieve;
if (fetchEvent.preloadResponse) {
retrieve = fetchEvent.preloadResponse;
} else {
retrieve = fetch(request);
}
const retrieve = fetchEvent.preloadResponse ? fetchEvent.preloadResponse : fetch(request);
addEventListener('fetch', fetchEvent => {
const request = fetchEvent.request;
if (request.headers.get('Accept').includes('text/html')) {
const retrieve = fetchEvent.preloadResponse ? fetchEvent.preloadResponse : fetch(request);
fetchEvent.respondWith(
retrieve
.then( responseFromRetrieve => {
// maybe cache this response for later here.
return responseFromRetrieve;
})
.catch( fetchError => {
return caches.match(request)
.then( responseFromCache => {
return responseFromCache || caches.match('/offline');
});
});
);
}
});

Jeremy Keith

Written by

A web developer and author living and working in Brighton, England.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade