Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-24 18:56:11 +01:00
forgejo/web_src/js/features/serviceworker.js
silverwind 3761bdb640
Fix serviceworker output file and misc improvements (#11562)
* Fix serviceworker output file and misc improvements

- Fix output file location for production build
- Cache more asset types: fonts and worker variants
- Parallelize a few tasks during initalization
- Only invalidate caches starting with our prefix
- Remove public/serviceworker.js before building
- Remove font preloads, they cause strange cors issues
- Misc eslint config adjustments

* remove webpack output files on watch-frontend
2020-05-24 08:36:40 +01:00

54 lines
1.6 KiB
JavaScript

const {UseServiceWorker, AppSubUrl, AppVer} = window.config;
const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script
async function unregister() {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map((registration) => {
return registration.active && registration.unregister();
}));
}
async function invalidateCache() {
const cacheKeys = await caches.keys();
await Promise.all(cacheKeys.map((key) => {
return key.startsWith(cachePrefix) && caches.delete(key);
}));
}
async function checkCacheValidity() {
const cacheKey = AppVer;
const storedCacheKey = localStorage.getItem('staticCacheKey');
// invalidate cache if it belongs to a different gitea version
if (cacheKey && storedCacheKey !== cacheKey) {
await invalidateCache();
localStorage.setItem('staticCacheKey', cacheKey);
}
}
export default async function initServiceWorker() {
if (!('serviceWorker' in navigator)) return;
if (UseServiceWorker) {
try {
// normally we'd serve the service worker as a static asset from StaticUrlPrefix but
// the spec strictly requires it to be same-origin so it has to be AppSubUrl to work
await Promise.all([
checkCacheValidity(),
navigator.serviceWorker.register(`${AppSubUrl}/serviceworker.js`),
]);
} catch (err) {
console.error(err);
await Promise.all([
invalidateCache(),
unregister(),
]);
}
} else {
await Promise.all([
invalidateCache(),
unregister(),
]);
}
}