irongit
defi_property/public/service-worker.js
93 lines4.1 KBJavaScript
1
2 // Based off of https://github.com/pwa-builder/PWABuilder/blob/main/docs/sw.js
3
4 /*
5 Welcome to our basic Service Worker! This Service Worker offers a basic offline experience
6 while also being easily customizeable. You can add in your own code to implement the capabilities
7 listed below, or change anything else you would like.
8
9
10 Need an introduction to Service Workers? Check our docs here: https://docs.pwabuilder.com/#/home/sw-intro
11 Want to learn more about how our Service Worker generation works? Check our docs here: https://docs.pwabuilder.com/#/studio/existing-app?id=add-a-service-worker
12
13 Did you know that Service Workers offer many more capabilities than just offline?
14 - Background Sync: https://microsoft.github.io/win-student-devs/#/30DaysOfPWA/advanced-capabilities/06
15 - Periodic Background Sync: https://web.dev/periodic-background-sync/
16 - Push Notifications: https://microsoft.github.io/win-student-devs/#/30DaysOfPWA/advanced-capabilities/07?id=push-notifications-on-the-web
17 - Badges: https://microsoft.github.io/win-student-devs/#/30DaysOfPWA/advanced-capabilities/07?id=application-badges
18 */
19
20 const HOSTNAME_WHITELIST = [
21 self.location.hostname,
22 'fonts.gstatic.com',
23 'fonts.googleapis.com',
24 'cdn.jsdelivr.net'
25 ]
26
27 // The Util Function to hack URLs of intercepted requests
28 const getFixedUrl = (req) => {
29 var now = Date.now()
30 var url = new URL(req.url)
31
32 // 1. fixed http URL
33 // Just keep syncing with location.protocol
34 // fetch(httpURL) belongs to active mixed content.
35 // And fetch(httpRequest) is not supported yet.
36 url.protocol = self.location.protocol
37
38 // 2. add query for caching-busting.
39 // Github Pages served with Cache-Control: max-age=600
40 // max-age on mutable content is error-prone, with SW life of bugs can even extend.
41 // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
42 // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
43 if (url.hostname === self.location.hostname) {
44 url.search += (url.search ? '&' : '?') + 'cache-bust=' + now
45 }
46 return url.href
47 }
48
49 /**
50 * @Lifecycle Activate
51 * New one activated when old isnt being used.
52 *
53 * waitUntil(): activating ====> activated
54 */
55 self.addEventListener('activate', event => {
56 event.waitUntil(self.clients.claim())
57 })
58
59 /**
60 * @Functional Fetch
61 * All network requests are being intercepted here.
62 *
63 * void respondWith(Promise<Response> r)
64 */
65 self.addEventListener('fetch', event => {
66 // Skip some of cross-origin requests, like those for Google Analytics.
67 if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
68 // Stale-while-revalidate
69 // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
70 // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
71 const cached = caches.match(event.request)
72 const fixedUrl = getFixedUrl(event.request)
73 const fetched = fetch(fixedUrl, { cache: 'no-store' })
74 const fetchedCopy = fetched.then(resp => resp.clone())
75
76 // Call respondWith() with whatever we get first.
77 // If the fetch fails (e.g disconnected), wait for the cache.
78 // If there’s nothing in cache, wait for the fetch.
79 // If neither yields a response, return offline pages.
80 event.respondWith(
81 Promise.race([fetched.catch(_ => cached), cached])
82 .then(resp => resp || fetched)
83 .catch(_ => { /* eat any errors */ })
84 )
85
86 // Update the cache with the version we fetched (only for ok status)
87 event.waitUntil(
88 Promise.all([fetchedCopy, caches.open("pwa-cache")])
89 .then(([response, cache]) => response.ok && cache.put(event.request, response))
90 .catch(_ => { /* eat any errors */ })
91 )
92 }
93 })