Skip to content

Commit

Permalink
Merge pull request #43 from SimonSiefke/add-navigation-preload
Browse files Browse the repository at this point in the history
add service worker navigation preload
  • Loading branch information
Rumyra authored Mar 18, 2022
2 parents d587747 + 2ed0eff commit f5c319b
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@ const putInCache = async (request, response) => {
await cache.put(request, response);
};

const cacheFirst = async ({ request, fallbackUrl }) => {
const cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}

// Next try to use the preloaded response, if it's there
const preloadResponse = await preloadResponsePromise;
if (preloadResponse) {
console.info('using preload response', preloadResponse);
putInCache(request, preloadResponse.clone());
return preloadResponse;
}

// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request);
Expand All @@ -37,6 +46,17 @@ const cacheFirst = async ({ request, fallbackUrl }) => {
}
};

const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) {
// Enable navigation preloads!
await self.registration.navigationPreload.enable();
}
};

self.addEventListener('activate', (event) => {
event.waitUntil(enableNavigationPreload());
});

self.addEventListener('install', (event) => {
event.waitUntil(
addResourcesToCache([
Expand All @@ -57,6 +77,7 @@ self.addEventListener('fetch', (event) => {
event.respondWith(
cacheFirst({
request: event.request,
preloadResponsePromise: event.preloadResponse,
fallbackUrl: '/sw-test/gallery/myLittleVader.jpg',
})
);
Expand Down

0 comments on commit f5c319b

Please sign in to comment.