1 /* ===========================================================
3 * ===========================================================
4 * Copyright 2016 @huxpro
5 * Licensed under Apache 2.0
6 * Register service worker.
7 * ========================================================== */
9 const RUNTIME
= 'docsify'
10 const HOSTNAME_WHITELIST
= [
11 self
.location
.hostname
,
13 'fonts.googleapis.com',
17 // The Util Function to hack URLs of intercepted requests
18 const getFixedUrl
= (req
) => {
20 var url
= new URL(req
.url
)
23 // Just keep syncing with location.protocol
24 // fetch(httpURL) belongs to active mixed content.
25 // And fetch(httpRequest) is not supported yet.
26 url
.protocol
= self
.location
.protocol
28 // 2. add query for caching-busting.
29 // Github Pages served with Cache-Control: max-age=600
30 // max-age on mutable content is error-prone, with SW life of bugs can even extend.
31 // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
32 // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
33 if (url
.hostname
=== self
.location
.hostname
) {
34 url
.search
+= (url
.search
? '&' : '?') + 'cache-bust=' + now
41 * New one activated when old isnt being used.
43 * waitUntil(): activating ====> activated
45 self
.addEventListener('activate', event
=> {
46 event
.waitUntil(self
.clients
.claim())
51 * All network requests are being intercepted here.
53 * void respondWith(Promise<Response> r)
55 self
.addEventListener('fetch', event
=> {
56 // Skip some of cross-origin requests, like those for Google Analytics.
57 if (HOSTNAME_WHITELIST
.indexOf(new URL(event
.request
.url
).hostname
) > -1) {
58 // Stale-while-revalidate
59 // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
60 // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
61 const cached
= caches
.match(event
.request
)
62 const fixedUrl
= getFixedUrl(event
.request
)
63 const fetched
= fetch(fixedUrl
, { cache
: 'no-store' })
64 const fetchedCopy
= fetched
.then(resp
=> resp
.clone())
66 // Call respondWith() with whatever we get first.
67 // If the fetch fails (e.g disconnected), wait for the cache.
68 // If there’s nothing in cache, wait for the fetch.
69 // If neither yields a response, return offline pages.
71 Promise
.race([fetched
.catch(_
=> cached
), cached
])
72 .then(resp
=> resp
|| fetched
)
73 .catch(_
=> { /* eat any errors */ })
76 // Update the cache with the version we fetched (only for ok status)
78 Promise
.all([fetchedCopy
, caches
.open(RUNTIME
)])
79 .then(([response
, cache
]) => response
.ok
&& cache
.put(event
.request
, response
))
80 .catch(_
=> { /* eat any errors */ })