1 |
|
2 | const serviceWorker = self;
|
3 |
|
4 | serviceWorker.workbox.skipWaiting();
|
5 | serviceWorker.workbox.clientsClaim();
|
6 |
|
7 | serviceWorker.workbox.setConfig({
|
8 | debug: serviceWorker.paw__env.PAW_ENV !== 'production',
|
9 | });
|
10 |
|
11 | const getOfflineHtml = () => {
|
12 | const scripts = serviceWorker.paw__offline_assets.filter(a => a.endsWith('.js')).map(js => `<script type="text/javascript" src="${js}" async></script>`).join('');
|
13 | return `<!DOCTYPE html><html><head></head><body><div id="${serviceWorker.paw__injected_variables.clientRootElementId}"></div>${scripts}</body></html>`;
|
14 | };
|
15 |
|
16 | serviceWorker.workbox.routing.registerRoute(
|
17 | new RegExp(`^${serviceWorker.location.origin}/.*__hmm_update.*`),
|
18 | serviceWorker.workbox.strategies.networkOnly(),
|
19 | );
|
20 |
|
21 | const assetsRegExp = /\.(css|js|jpg|png|jpeg|gif|woff|woff2|ttf|eot|ico|mp4|avi)$/;
|
22 |
|
23 | const networkFirstHandler = serviceWorker.workbox.strategies.networkFirst();
|
24 | const cacheFirstHandler = serviceWorker.workbox.strategies.cacheFirst();
|
25 | const staleHandler = serviceWorker.workbox.strategies.staleWhileRevalidate();
|
26 |
|
27 | serviceWorker.workbox.routing.setDefaultHandler(({ event }) => {
|
28 | const { request } = event;
|
29 | const requestMethod = request.method.toUpperCase();
|
30 |
|
31 | if (requestMethod !== 'GET') {
|
32 | return fetch(event.request);
|
33 | }
|
34 |
|
35 | if (
|
36 | request.url.indexOf(serviceWorker.location.origin) !== -1
|
37 | && assetsRegExp.test(request.url)
|
38 | ) {
|
39 | return cacheFirstHandler.handle({ event });
|
40 | }
|
41 |
|
42 | if (
|
43 | request.url.indexOf(serviceWorker.location.origin) === -1
|
44 | && assetsRegExp.test(request.url)
|
45 | ) {
|
46 | return staleHandler.handle({ event });
|
47 | }
|
48 |
|
49 | if (
|
50 | request.url.indexOf(serviceWorker.location.origin) !== -1
|
51 | && request.headers.get('accept').indexOf('html') !== -1
|
52 | ) {
|
53 | return networkFirstHandler.handle({ event }).then((response) => {
|
54 | if (!response) {
|
55 | return new Response(
|
56 | getOfflineHtml(),
|
57 | { headers: { 'Content-Type': 'text/html' } },
|
58 | );
|
59 | }
|
60 | return response;
|
61 | });
|
62 | }
|
63 |
|
64 | return networkFirstHandler.handle({ event });
|
65 | });
|
66 |
|
67 |
|
68 | serviceWorker.workbox.precaching.precacheAndRoute(serviceWorker.__precacheManifest);
|