feat: use network first caching strategy
This commit is contained in:
parent
17c6dd2578
commit
084dda5c65
2 changed files with 44 additions and 70 deletions
|
@ -1,5 +1,5 @@
|
||||||
import { defineConfig } from 'astro/config';
|
import { defineConfig } from 'astro/config';
|
||||||
// import serviceWorker from '@ayco/astro-sw';
|
import serviceWorker from '@ayco/astro-sw';
|
||||||
import sitemap from "@astrojs/sitemap";
|
import sitemap from "@astrojs/sitemap";
|
||||||
|
|
||||||
// https://astro.build/config
|
// https://astro.build/config
|
||||||
|
@ -7,17 +7,22 @@ export default defineConfig({
|
||||||
site: 'https://ayo.ayco.io',
|
site: 'https://ayo.ayco.io',
|
||||||
integrations: [
|
integrations: [
|
||||||
sitemap(),
|
sitemap(),
|
||||||
// serviceWorker({
|
serviceWorker({
|
||||||
// path: './src/sw.mjs',
|
path: './src/sw.mjs',
|
||||||
// assetCachePrefix: 'ayco-personal-site',
|
assetCachePrefix: 'ayco-personal-site',
|
||||||
// assetCacheVersionID: 'hey-mama',
|
assetCacheVersionID: '2',
|
||||||
// logAssets: true,
|
logAssets: true,
|
||||||
// excludeRoutes: [
|
excludeRoutes: [
|
||||||
// '/threads'
|
'/threads'
|
||||||
// ],
|
],
|
||||||
// esbuild: {
|
esbuild: {
|
||||||
// minify: true
|
minify: true
|
||||||
// }
|
},
|
||||||
// })
|
registrationHooks: {
|
||||||
|
afterRegistration: () => {
|
||||||
|
console.log('>>> registered sw')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
83
src/sw.mjs
83
src/sw.mjs
|
@ -4,66 +4,32 @@
|
||||||
* @see https://ayco.io/n/@ayco/astro-sw
|
* @see https://ayco.io/n/@ayco/astro-sw
|
||||||
*/
|
*/
|
||||||
const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}`
|
const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}`
|
||||||
|
const forceLogging = true;
|
||||||
const cleanOldCaches = async () => {
|
|
||||||
const allowCacheNames = ['cozy-reader', cacheName];
|
|
||||||
const allCaches = await caches.keys();
|
|
||||||
allCaches.forEach(key => {
|
|
||||||
if (!allowCacheNames.includes(key)) {
|
|
||||||
caches.delete(key);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const addResourcesToCache = async (resources) => {
|
const addResourcesToCache = async (resources) => {
|
||||||
const cache = await caches.open(cacheName);
|
const cache = await caches.open(cacheName);
|
||||||
await cache.addAll(resources);
|
console.info('adding resources to cache...', { force: !!forceLogging, context: 'ayco-sw', data: resources })
|
||||||
|
try {
|
||||||
|
await cache.addAll(resources);
|
||||||
|
} catch(error) {
|
||||||
|
console.error('failed to add resources to cache; make sure requests exists and that there are no duplicates', error);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const putInCache = async (request, response) => {
|
const putInCache = async (request, response) => {
|
||||||
const cache = await caches.open(cacheName);
|
const cache = await caches.open(cacheName);
|
||||||
// if exists, replace
|
|
||||||
|
|
||||||
const keys = await cache.keys();
|
if (response.ok) {
|
||||||
if (keys.includes(request)) {
|
console.info('adding one response to cache...', request.url)
|
||||||
cache.delete(request);
|
cache.put(request, response);
|
||||||
}
|
}
|
||||||
|
|
||||||
await cache.put(request, response);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const cacheAndRevalidate = async ({ request, preloadResponsePromise, fallbackUrl }) => {
|
const networkFirst = async ({ request, fallbackUrl }) => {
|
||||||
|
|
||||||
const cache = await caches.open(cacheName);
|
const cache = await caches.open(cacheName);
|
||||||
|
|
||||||
// Try get the resource from the cache
|
|
||||||
const responseFromCache = await cache.match(request);
|
|
||||||
if (responseFromCache) {
|
|
||||||
// get network response for revalidation of cached assets
|
|
||||||
fetch(request.clone()).then((responseFromNetwork) => {
|
|
||||||
if (responseFromNetwork) {
|
|
||||||
putInCache(request, responseFromNetwork.clone());
|
|
||||||
}
|
|
||||||
}).catch((error) => {
|
|
||||||
logError('failed to fetch updated resource', { force: forceLogging, context: 'cozy-sw', data: error })
|
|
||||||
});
|
|
||||||
|
|
||||||
return responseFromCache;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to use the preloaded response, if it's there
|
|
||||||
// NOTE: Chrome throws errors regarding preloadResponse, see:
|
|
||||||
// https://bugs.chromium.org/p/chromium/issues/detail?id=1420515
|
|
||||||
// https://github.com/mdn/dom-examples/issues/145
|
|
||||||
// To avoid those errors, remove or comment out this block of preloadResponse
|
|
||||||
// code along with enableNavigationPreload() and the "activate" listener.
|
|
||||||
const preloadResponse = await preloadResponsePromise;
|
|
||||||
if (preloadResponse) {
|
|
||||||
putInCache(request, preloadResponse.clone());
|
|
||||||
return preloadResponse;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Try to get the resource from the network for 5 seconds
|
// Try to get the resource from the network for 5 seconds
|
||||||
const responseFromNetwork = await fetch(request.clone());
|
const responseFromNetwork = await fetch(request.clone());
|
||||||
|
@ -71,13 +37,22 @@ const cacheAndRevalidate = async ({ request, preloadResponsePromise, fallbackUrl
|
||||||
// we need to save clone to put one copy in cache
|
// we need to save clone to put one copy in cache
|
||||||
// and serve second one
|
// and serve second one
|
||||||
putInCache(request, responseFromNetwork.clone());
|
putInCache(request, responseFromNetwork.clone());
|
||||||
|
console.info('using network response', responseFromNetwork.url);
|
||||||
return responseFromNetwork;
|
return responseFromNetwork;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
||||||
|
// Try get the resource from the cache
|
||||||
|
const responseFromCache = await cache.match(request);
|
||||||
|
if (responseFromCache) {
|
||||||
|
console.info('using cached response...', responseFromCache.url);
|
||||||
|
return responseFromCache;
|
||||||
|
}
|
||||||
|
|
||||||
// Try the fallback
|
// Try the fallback
|
||||||
const fallbackResponse = await cache.match(fallbackUrl);
|
const fallbackResponse = await cache.match(fallbackUrl);
|
||||||
if (fallbackResponse) {
|
if (fallbackResponse) {
|
||||||
|
console.info('using fallback cached response...', fallbackResponse.url)
|
||||||
return fallbackResponse;
|
return fallbackResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -91,20 +66,13 @@ const cacheAndRevalidate = async ({ request, preloadResponsePromise, fallbackUrl
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const enableNavigationPreload = async () => {
|
|
||||||
if (self.registration.navigationPreload) {
|
|
||||||
// Enable navigation preloads!
|
|
||||||
await self.registration.navigationPreload.enable();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
self.addEventListener('activate', (event) => {
|
self.addEventListener('activate', (event) => {
|
||||||
cleanOldCaches();
|
console.info('activating service worker...')
|
||||||
event.waitUntil(enableNavigationPreload());
|
|
||||||
});
|
});
|
||||||
|
|
||||||
self.addEventListener('install', (event) => {
|
self.addEventListener('install', (event) => {
|
||||||
|
|
||||||
|
console.info('installing service worker...')
|
||||||
self.skipWaiting(); // go straight to activate
|
self.skipWaiting(); // go straight to activate
|
||||||
|
|
||||||
event.waitUntil(
|
event.waitUntil(
|
||||||
|
@ -113,11 +81,12 @@ self.addEventListener('install', (event) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', (event) => {
|
||||||
|
console.info('fetch happened', {data: event});
|
||||||
|
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
cacheAndRevalidate({
|
networkFirst({
|
||||||
request: event.request,
|
request: event.request,
|
||||||
preloadResponsePromise: event.preloadResponse,
|
|
||||||
fallbackUrl: './',
|
fallbackUrl: './',
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
Loading…
Reference in a new issue