Skip to content

Commit

Permalink
fix: adding back the service worker
Browse files Browse the repository at this point in the history
It was mistakenly removed in 4c71c4a
  • Loading branch information
divdavem committed Aug 18, 2023
1 parent 53dbb7a commit f4dadf4
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions demo/src/service-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="webworker" />

declare const self: ServiceWorkerGlobalScope;

import {build, files, prerendered, version} from '$service-worker';

const CACHE = `cache-${version}`;

const ASSETS = [...build.map((file) => file.replace(/\/index\.html$/, '/')), ...prerendered, ...files];

const splitAssets = (assets: string[]) => {
const withHash: string[] = [];
const withoutHash: string[] = [];
const hashRegExp = /[.-]\w{8,}\.\w{2,4}$/;
for (const asset of assets) {
(hashRegExp.test(asset) ? withHash : withoutHash).push(asset);
}
return {withHash, withoutHash};
};

self.addEventListener('install', (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE);
const {withHash, withoutHash} = splitAssets(ASSETS);
const missingWithHash: string[] = [];
await Promise.all(
withHash.map(async (url) => {
const response = await caches.match(url);
if (response?.ok) {
cache.put(url, response);
} else {
missingWithHash.push(url);
}
})
);
await cache.addAll([...missingWithHash, ...withoutHash]);
await self.skipWaiting();
})()
);
});

self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
await self.clients.claim();
await Promise.all((await caches.keys()).filter((key) => key !== CACHE).map((key) => caches.delete(key)));
})()
);
});

self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.method === 'GET' && ASSETS.includes(url.pathname)) {
event.respondWith(
(async () => {
const cache = await caches.open(CACHE);
const response = await cache.match(url.pathname);
return response!;
})()
);
}
});

0 comments on commit f4dadf4

Please sign in to comment.