Les service workers agissent comme des serveurs proxy qui gèrent les requêtes réseau au sein de
votre application. Cela rend possible le fonctionnement hors-ligne de votre application, mais même
si vous n’avez pas besoin de support hors-ligne (ou si vous ne pouvez pas réalistiquement
l’implémenter à cause du type d’application que vous développez), il est souvent utile d’utiliser
les service workers pour accélérer la navigation en pré-cachant vos JS et CSS compilés.
Dans SvelteKit, si vous avez un fichier src/service-worker/index.ts, celui-ci sera compilé et
automatiquement activé.
src/service-worker.ts ok .js est également valide, voir la section sur le
typage ci-dessous.
Au sein du service worker
Pour que le service worker puisse être effectif, vous aurez probablement besoin d’importer certaines
choses :
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a tsconfig.json that extends $app/tsconfig/service-worker.
An array of { path: string } objects representing the files generated by Vite.
The path is relative to the base path, and is intended for use with cache.add(...) inside a service worker.
During development, this is an empty array.
An array of { path: AssetPath } objects representing the files in your static directory, or whatever directory is specified by config.files.assets.
The path is relative to the base path, and can be used with asset(...).
Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
In hash routing mode, the returned URL starts with #.
During server rendering, the base path is relative and depends on the page currently being rendered.
import{resolve}from'$app/paths';// using a pathnameconstresolved=resolve(`blog/hello-world`);// using a route ID plus parametersconstresolved=resolve('/blog/[slug]',{slug:'hello-world'});
2.26
}from'$app/paths';// Crée un nom de cache unique pour ce déploiement
constCACHEconstCACHE:string=`cache-${version(alias)constversion:stringimportversion
The value of config.version.name.
}`;// les chemins `immutable`/`assets` importés depuis `$app/manifest` sont relatifs au chemin de base,
// résolvez-les donc en chemins absolus pouvant correspondre à `url.pathname` du gestionnaire
// `fetch`
constASSETSconstASSETS:string[]=[...immutable(alias)constimmutable:{path:string;}[]importimmutable
An array of { path: string } objects representing the files generated by Vite.
The path is relative to the base path, and is intended for use with cache.add(...) inside a service worker.
During development, this is an empty array.
Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
In hash routing mode, the returned URL starts with #.
During server rendering, the base path is relative and depends on the page currently being rendered.
import{resolve}from'$app/paths';// using a pathnameconstresolved=resolve(`blog/hello-world`);// using a route ID plus parametersconstresolved=resolve('/blog/[slug]',{slug:'hello-world'});
2.26
(asset(parameter)asset:{path:string;}.path(property)path:string)),// la sortie générée par Vite...assets(alias)constassets:{path:AssetPath;}[]importassets
An array of { path: AssetPath } objects representing the files in your static directory, or whatever directory is specified by config.files.assets.
The path is relative to the base path, and can be used with asset(...).
Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
In hash routing mode, the returned URL starts with #.
During server rendering, the base path is relative and depends on the page currently being rendered.
import{resolve}from'$app/paths';// using a pathnameconstresolved=resolve(`blog/hello-world`);// using a route ID plus parametersconstresolved=resolve('/blog/[slug]',{slug:'hello-world'});
2.26
(asset(parameter)asset:{path:AssetPath;}.path(property)path:string))// tout ce qui est dans `static`];self(alias)constself:ServiceWorkerGlobalScopeimportself
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a tsconfig.json that extends $app/tsconfig/service-worker.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
('install',(event(parameter)event:ExtendableEvent)=>{ // Crée un nouveau cache et y ajoute tous les fichiers
asyncfunctionaddFilesToCache(localfunction)addFilesToCache():Promise<void>(){constcacheconstcache:Cache=awaitcachesvarcaches:CacheStorage
The addAll() method of the Cache interface takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache. The request objects created during retrieval become keys to the stored response operations.
The ExtendableEvent.waitUntil() method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a tsconfig.json that extends $app/tsconfig/service-worker.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
('activate',(event(parameter)event:ExtendableEvent)=>{ // Supprime du disque les données précédemment mises en cache
asyncfunctiondeleteOldCaches(localfunction)deleteOldCaches():Promise<void>(){for(constkeyconstkey:stringofawaitcachesvarcaches:CacheStorage
The keys() method of the CacheStorage interface returns a Promise that will resolve with an array containing strings corresponding to all of the named Cache objects tracked by the CacheStorage object in the order they were created. Use this method to iterate over a list of all Cache objects.
The delete() method of the CacheStorage interface finds the Cache object matching the cacheName, and if found, deletes the Cache object and returns a Promise that resolves to true. If no Cache object is found, it resolves to false.
The ExtendableEvent.waitUntil() method tells the event dispatcher that work is ongoing. It can also be used to detect whether that work was successful. In service workers, waitUntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.
The execution context of a service worker. This export exists to make it easier to
use service workers with the correct types, provided the importing module is governed
by a tsconfig.json that extends $app/tsconfig/service-worker.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
('fetch',(event(parameter)event:FetchEvent)=>{ // ignore les requêtes POST, etc
if(event(parameter)event:FetchEvent.request(property)FetchEvent.request:Request
The request read-only property of the FetchEvent interface returns the Request that triggered the event handler.
The URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
(CACHEconstCACHE:string); // les fichiers `immutable`/`assets` peuvent toujours être servis depuis le cache
if(ASSETSconstASSETS:string[].includes(method)Array<string>.includes(searchElement:string,fromIndex?:number):boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
The match() method of the Cache interface returns a Promise that resolves to the Response associated with the first matching request in the Cache object. If no match is found, the Promise resolves to undefined.
The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character.
);if(responseconstresponse:Response|undefined){returnresponseconstresponse:Response;}} // pour tout le reste, tester d'abord le réseau...
try{constresponseconstresponse:Response=awaitfetchfunctionfetch(input:string|URL|Request,init?:RequestInit):Promise<Response>(+2overloads)
The get() method of the Headers interface returns a byte string of all the values of a header within a Headers object with a given name. If the requested header doesn't exist in the Headers object, it returns null.
Returns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
searchString
search string
position
If position is undefined, 0 is assumed, so as to search all of the String.
('no-store')){ // ... et mettez les réponses en cache pour la prochaine fois...
voidcacheconstcache:Cache.put(method)Cache.put(request:RequestInfo|URL,response:Response):Promise<void>(+1overload)
The put() method of the Cache interface allows key/value pairs to be added to the current Cache object.
());}returnresponseconstresponse:Response;}catch(error(localvar)error:unknown){ // ... et sinon, servez les données précédemment mises en cache si elles existent...
constresponseconstresponse:Response|undefined=awaitcacheconstcache:Cache.match(method)Cache.match(request:RequestInfo|URL,options?:CacheQueryOptions):Promise<Response|undefined>(+1overload)
The match() method of the Cache interface returns a Promise that resolves to the Response associated with the first matching request in the Cache object. If no match is found, the Promise resolves to undefined.
);if(responseconstresponse:Response|undefined){returnresponseconstresponse:Response;} // ... ou bien jetez une exception
throwerror(localvar)error:unknown;}}event(parameter)event:FetchEvent.respondWith(method)FetchEvent.respondWith(r:Response|PromiseLike<Response>):void
The respondWith() method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.
Faites attention lorsque vous mettez des choses en cache ! Dans certains cas, des données
périmées peuvent être pires que pas de données du tout en mode hors-ligne. Puisque les navigateurs
vont vider le cache s’il remplit trop, vous devriez également faire attention lorsque vous mettez
en cache des assets de grande taille comme des fichiers vidéo.
Typage
Les service workers sont exécutés dans un contexte différent du reste de votre application. Ils
nécessitent donc des types différents. Vous devez vous assurez que la racine de votre projet
tsconfig.json exclue le code de votre service worker...
... et que votre fichier src/service-worker/index.ts soit placé à côté d’un tsconfig.json
distinct, ce qui devrait définir correctement vos types si vous héritez de
$app/tsconfig/service-worker :
src/service-worker/tsconfig
{"extends":"$app/tsconfig/service-worker"}
Activation manuelle
Vous pouvez désactiver l’activation automatique si vous avez
besoin de définir le service worker avec votre propre logique. La définition par défaut, qui est
injectée dans du HTML rendu sur le serveur, ressemble à quelque chose comme ça :
The Window.navigator read-only property returns a reference to the Navigator object, which has methods and properties about the application running the script.
The Window.navigator read-only property returns a reference to the Navigator object, which has methods and properties about the application running the script.
The serviceWorker read-only property of the Navigator interface returns the ServiceWorkerContainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the ServiceWorker.
Available only in secure contexts.
Le service worker est compilé pour la production, mais pas lors du développement.
Mettre à jour le service worker
Les navigateurs vérifient si un service worker à jour est disponible lorsqu’une navigation “de
pleine page” se produit au sein de son scope, et après des évènements fonctionnels comme push et
sync. Les clients côté client ne sont ni l’un ni l’autre, ce qui implique qu’une navigation au
sein de votre application ne va en soi provoquer un nouveau déploiement de service worker.
SvelteKit exécute
registration.update()
uniquement en tant que partie de la gestion d’erreur — si un module de route échoue à se charger ou
si une navigation résulte en un statut d’erreur, et que le polling de
version détecte que l’application a été redéployée, le service worker
sera mis à jour avant que SvelteKit ne déclenche une navigation complète pour se mettre à jour.
Si vous souhaitez que les nouveaux déploiements soient pris en compte de manière plus agressive,
vous pouvez déclencher vous-même une vérification des mises à jour — par exemple pour chaque
navigation côté client, dans votre layout racine :
The Window.navigator read-only property returns a reference to the Navigator object, which has methods and properties about the application running the script.
The Window.navigator read-only property returns a reference to the Navigator object, which has methods and properties about the application running the script.
The serviceWorker read-only property of the Navigator interface returns the ServiceWorkerContainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the ServiceWorker.
Available only in secure contexts.
The getRegistration() method of the ServiceWorkerContainer interface gets a ServiceWorkerRegistration object whose scope URL matches the provided client URL. The method returns a Promise that resolves to a ServiceWorkerRegistration or undefined.
The update() method of the ServiceWorkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago.
Ceci ne va pas faire en sorte que le nouveau service worker (s’il existe) se mette en place sur la
page existante immédiatement — à la place, ce nouveau service worker sera installé en toile de fond,
et il se mettra en place dès que le nombre d’onglets gérés par le service worker actuel tombera à
zéro.
Autres solutions
L’implémentation du service worker de SvelteKit est conçue pour être simple d’usage et est
probablement une bonne solution pour la plupart des gens. Cependant, en dehors de SvelteKit,
beaucoup d’applications PWA utilisent la librairie Workbox. Si
vous êtes habitué•e à cette librairie, vous pourriez préférer l’usage du plugin PWA de
Vite.
Références
Pour plus d’informations sur les service workers de manière générale, nous recommandons la
documentation de
MDN.