Skip to content

Commit 0984794

Browse files
dummdidummbenmccannRich-Harris
authored
[docs] add service-worker example (sveltejs#7461)
* [docs] service worker * Update documentation/docs/30-advanced/40-service-workers.md Co-authored-by: Ben McCann <[email protected]> * Update documentation/docs/30-advanced/40-service-workers.md Co-authored-by: Ben McCann <[email protected]> * Update documentation/docs/30-advanced/40-service-workers.md Co-authored-by: Ben McCann <[email protected]> * minor tweaks * network-first service worker strategy (sveltejs#7832) * network-first strategy * only cache 200 responses Co-authored-by: Ben McCann <[email protected]> Co-authored-by: Rich Harris <[email protected]> Co-authored-by: Rich Harris <[email protected]>
1 parent 0932131 commit 0984794

File tree

1 file changed

+85
-4
lines changed

1 file changed

+85
-4
lines changed

documentation/docs/30-advanced/40-service-workers.md

+85-4
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,88 @@ title: Service workers
44

55
Service workers act as proxy servers that handle network requests inside your app. This makes it possible to make your app work offline, but even if you don't need offline support (or can't realistically implement it because of the type of app you're building), it's often worth using service workers to speed up navigation by precaching your built JS and CSS.
66

7-
In SvelteKit, if you have a `src/service-worker.js` file (or `src/service-worker.ts`, or `src/service-worker/index.js`, etc) it will be built with Vite and automatically registered. You can disable automatic registration if you need to register the service worker with your own logic (e.g. prompt user for update, configure periodic updates, use `workbox`, etc).
7+
In SvelteKit, if you have a `src/service-worker.js` file (or `src/service-worker.ts`, `src/service-worker/index.js`, etc) it will be bundled and automatically registered. You can change the [location of your service worker](/docs/configuration#files) if you need to.
88

9-
> You can change the [location of your service worker](/docs/configuration#files) and [disable automatic registration](/docs/configuration#serviceworker) in your project configuration.
9+
You can [disable automatic registration](/docs/configuration#serviceworker) if you need to register the service worker with your own logic or use another solution. The default registration looks something like this:
1010

11-
Inside the service worker you have access to the [`$service-worker` module](/docs/modules#$service-worker). If your Vite config specifies `define`, this will be applied to service workers as well as your server/client builds.
11+
```js
12+
if ('serviceWorker' in navigator) {
13+
addEventListener('load', function () {
14+
navigator.serviceWorker.register('./path/to/service-worker.js');
15+
});
16+
}
17+
```
18+
19+
Inside the service worker you have access to the [`$service-worker` module](/docs/modules#$service-worker), which provides you with the paths to all static assets, build files and prerendered pages. You're also provided with an app version string which you can use for creating a unique cache name. If your Vite config specifies `define` (used for global variable replacements), this will be applied to service workers as well as your server/client builds.
20+
21+
The following example caches the built app and any files in `static` eagerly, and caches all other requests as they happen. This would make each page work offline once visited.
22+
23+
```js
24+
// @ts-nocheck Official TS Service Worker typings are still a work in progress.
25+
import { build, files, version } from '$service-worker';
26+
27+
// Create a unique cache name for this deployment
28+
const CACHE = `cache-${version}`;
29+
30+
const ASSETS = [
31+
...build, // the app itself
32+
...files // everything in `static`
33+
];
34+
35+
self.addEventListener('install', (event) => {
36+
// Create a new cache and add all files to it
37+
async function addFilesToCache() {
38+
const cache = await caches.open(CACHE);
39+
await cache.addAll(ASSETS);
40+
}
41+
42+
event.waitUntil(addFilesToCache());
43+
});
44+
45+
self.addEventListener('activate', (event) => {
46+
// Remove previous cached data from disk
47+
async function deleteOldCaches() {
48+
for (const key of await caches.keys()) {
49+
if (key !== CACHE) await caches.delete(key);
50+
}
51+
}
52+
53+
event.waitUntil(deleteOldCaches());
54+
});
55+
56+
self.addEventListener('fetch', (event) => {
57+
// ignore POST requests etc
58+
if (event.request.method !== 'GET') return;
59+
60+
async function respond() {
61+
const url = new URL(event.request.url);
62+
const cache = await caches.open(CACHE);
63+
64+
// `build`/`files` can always be served from the cache
65+
if (ASSETS.includes(url.pathname)) {
66+
return cache.match(event.request);
67+
}
68+
69+
// for everything else, try the network first, but
70+
// fall back to the cache if we're offline
71+
try {
72+
const response = await fetch(event.request);
73+
74+
if (response.status === 200) {
75+
cache.put(response.clone());
76+
}
77+
78+
return response;
79+
} catch {
80+
return cache.match(event.request);
81+
}
82+
}
83+
84+
event.respondWith(respond());
85+
});
86+
```
87+
88+
> Be careful when caching! In some cases, stale data might be worse than data that's unavailable while offline. Since browsers will empty caches if they get too full, you should also be careful about caching large assets like video files.
1289
1390
The service worker is bundled for production, but not during development. For that reason, only browsers that support [modules in service workers](https://web.dev/es-modules-in-sw) will be able to use them at dev time. If you are manually registering your service worker, you will need to pass the `{ type: 'module' }` option in development:
1491

@@ -18,4 +95,8 @@ import { dev } from '$app/environment';
1895
navigator.serviceWorker.register('/service-worker.js', {
1996
type: dev ? 'module' : 'classic'
2097
});
21-
```
98+
```
99+
100+
> `build` and `prerendered` are empty arrays during development
101+
102+
SvelteKit's service worker implementation is deliberately low-level. If you need a more full-flegded but also more opinionated solution, we recommend looking at solutions like [Vite PWA plugin](https://vite-pwa-org.netlify.app/frameworks/sveltekit.html), which uses [Workbox](https://web.dev/learn/pwa/workbox). For more general information on service workers, we recommend [the MDN web docs](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers).

0 commit comments

Comments
 (0)