]> git.r.bdr.sh - rbdr/r.bdr.sh/blame_incremental - service_worker.js
Update code block
[rbdr/r.bdr.sh] / service_worker.js
... / ...
CommitLineData
1'use strict';
2
3const internals = {
4 version: '4.2.0',
5 offlineEssentials: [
6 '/',
7 '/css/application.css'
8 ],
9
10 // Response for when network is not available
11
12 errorResponse: '<h1>Service Unavailable</h1>',
13
14 // Main entry point, adds event listeners for service worker
15
16 main() {
17
18 self.addEventListener('install', internals.onInstall);
19 self.addEventListener('fetch', internals.onFetch);
20 self.addEventListener('activate', internals.onActivate);
21 },
22
23 // Runs on installation of the service worker
24
25 onInstall(event) {
26
27 event.waitUntil(
28 caches.open(`${internals.version}/essentials`)
29 .then((cache) => {
30
31 return cache.addAll(internals.offlineEssentials)
32 })
33 );
34 },
35
36 // Runs when a path is fetched, returns files from cache
37
38 onFetch(event) {
39
40 if (event.request.method !== 'GET') {
41 return;
42 }
43
44 event.respondWith(
45 caches.match(event.request)
46 .then((cached) => {
47
48 const freshContent = fetch(event.request)
49 .then((response) => {
50
51 caches.open(`${internals.version}/paths`)
52 .then((cache) => cache.put(event.request, response.clone()));
53 }, internals.onFetchFail)
54 .catch(internals.onFetchFail);
55
56 return cached || freshContent;
57 })
58 );
59 },
60
61 onActivate(event) {
62
63 event.waitUntil(
64 caches.keys()
65 .then((keys) => {
66
67 return Promise.all(keys
68 .filter((key) => !key.startsWith(internals.version))
69 .map((key) => caches.delete(key))
70 );
71 })
72 );
73 },
74
75 // Responds with Servie Unavailable if we can't fetch a
76 // file from network
77
78 onFetchFail() {
79
80 return new Response(internals.errorResponse, {
81 status: 503,
82 statusText: 'Service Unavailable',
83 headers: new Headers({
84 'Content-Type': 'text/html'
85 })
86 });
87 }
88};
89
90internals.main();