2017-02-21 22:16:10 +08:00
# Offline Mode
2017-03-10 05:19:07 +08:00
[Progressive Web Apps ](https://developers.google.com/web/progressive-web-apps/ ) (PWA) are experiences that combine the best of the web with the best of apps. We can enhance our website with service workers to work **offline** or on low-quality networks.
2021-07-31 00:37:52 +08:00
It is also very easy to use.
2017-02-21 22:16:10 +08:00
2017-02-21 23:00:22 +08:00
## Create serviceWorker
2017-03-10 05:19:07 +08:00
2021-07-31 00:37:52 +08:00
Create a `sw.js` file in your project's root directory and copy the following code:
2017-02-21 22:16:10 +08:00
2023-08-09 17:53:30 +08:00
_sw.js_
2017-02-21 22:16:10 +08:00
```js
/* ===========================================================
* docsify sw.js
* ===========================================================
* Copyright 2016 @huxpro
* Licensed under Apache 2.0
* Register service worker.
* ========================================================== */
2023-08-09 17:53:30 +08:00
const RUNTIME = 'docsify';
2017-02-21 22:16:10 +08:00
const HOSTNAME_WHITELIST = [
self.location.hostname,
'fonts.gstatic.com',
2017-02-22 09:39:17 +08:00
'fonts.googleapis.com',
2023-08-09 17:53:30 +08:00
'cdn.jsdelivr.net',
];
2017-02-21 22:16:10 +08:00
// The Util Function to hack URLs of intercepted requests
2023-08-09 17:53:30 +08:00
const getFixedUrl = req => {
const now = Date.now();
const url = new URL(req.url);
2017-02-21 22:16:10 +08:00
// 1. fixed http URL
// Just keep syncing with location.protocol
// fetch(httpURL) belongs to active mixed content.
// And fetch(httpRequest) is not supported yet.
2023-08-09 17:53:30 +08:00
url.protocol = self.location.protocol;
2017-02-21 22:16:10 +08:00
// 2. add query for caching-busting.
// Github Pages served with Cache-Control: max-age=600
// max-age on mutable content is error-prone, with SW life of bugs can even extend.
// Until cache mode of Fetch API landed, we have to workaround cache-busting with query string.
// Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190
2017-02-22 09:39:17 +08:00
if (url.hostname === self.location.hostname) {
2023-08-09 17:53:30 +08:00
url.search += (url.search ? '& ' : '?') + 'cache-bust=' + now;
2017-02-22 09:39:17 +08:00
}
2023-08-09 17:53:30 +08:00
return url.href;
};
2017-02-21 22:16:10 +08:00
/**
* @Lifecycle Activate
* New one activated when old isnt being used.
*
* waitUntil(): activating ====> activated
*/
2017-02-22 09:39:17 +08:00
self.addEventListener('activate', event => {
2023-08-09 17:53:30 +08:00
event.waitUntil(self.clients.claim());
});
2017-02-21 22:16:10 +08:00
/**
* @Functional Fetch
* All network requests are being intercepted here.
*
2017-02-22 09:39:17 +08:00
* void respondWith(Promise< Response > r)
2017-02-21 22:16:10 +08:00
*/
self.addEventListener('fetch', event => {
// Skip some of cross-origin requests, like those for Google Analytics.
if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) {
// Stale-while-revalidate
// similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale
// Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1
2023-08-09 17:53:30 +08:00
const cached = caches.match(event.request);
const fixedUrl = getFixedUrl(event.request);
const fetched = fetch(fixedUrl, { cache: 'no-store' });
const fetchedCopy = fetched.then(resp => resp.clone());
2017-02-21 22:16:10 +08:00
// Call respondWith() with whatever we get first.
// If the fetch fails (e.g disconnected), wait for the cache.
// If there’ s nothing in cache, wait for the fetch.
// If neither yields a response, return offline pages.
event.respondWith(
Promise.race([fetched.catch(_ => cached), cached])
.then(resp => resp || fetched)
2023-08-09 17:53:30 +08:00
.catch(_ => {
/* eat any errors */
})
);
2017-02-21 22:16:10 +08:00
// Update the cache with the version we fetched (only for ok status)
event.waitUntil(
Promise.all([fetchedCopy, caches.open(RUNTIME)])
2023-08-09 17:53:30 +08:00
.then(
([response, cache]) =>
response.ok & & cache.put(event.request, response)
)
.catch(_ => {
/* eat any errors */
})
);
2017-02-21 22:16:10 +08:00
}
2023-08-09 17:53:30 +08:00
});
2017-02-21 22:16:10 +08:00
```
## Register
2021-07-31 00:37:52 +08:00
Now, register it in your `index.html` . It only works on some modern browsers, so we need to check:
2017-02-21 22:16:10 +08:00
2023-08-09 17:53:30 +08:00
_index.html_
2017-02-21 22:16:10 +08:00
```html
< script >
if (typeof navigator.serviceWorker !== 'undefined') {
2023-08-09 17:53:30 +08:00
navigator.serviceWorker.register('sw.js');
2017-02-21 22:16:10 +08:00
}
< / script >
```
## Enjoy it
2021-07-31 00:37:52 +08:00
Release your website and start experiencing the magical offline feature. :ghost: You can turn off Wi-Fi and refresh the current site to experience it.