mirror of
https://gitee.com/docsifyjs/docsify.git
synced 2024-12-05 21:50:29 +08:00
116 lines
4.0 KiB
Markdown
116 lines
4.0 KiB
Markdown
# Offline Modus
|
||
|
||
[Progressive Web Apps](https://developers.google.com/web/progressive-web-apps/) (PWA) sind Erfahrungen die Vorzüge des Internets mit den Vorzügen von Apps verbinden. Wir können unsere Webseite verbessern, indem wir sie mit Hilfe von service workers auch **offline** und in schlechten Netzen interagierbar machen.
|
||
|
||
Sie sind sehr einfach zu verwenden.
|
||
|
||
## serviceWorker erstellen
|
||
|
||
Erstelle eine Datei namens `sw.js` in deinem **docsify** Verzeichnis und kopiere folgenden Code:
|
||
|
||
*sw.js*
|
||
|
||
```js
|
||
/* ===========================================================
|
||
* docsify sw.js
|
||
* ===========================================================
|
||
* Copyright 2016 @huxpro
|
||
* Licensed under Apache 2.0
|
||
* Register service worker.
|
||
* ========================================================== */
|
||
|
||
const RUNTIME = 'docsify'
|
||
const HOSTNAME_WHITELIST = [
|
||
self.location.hostname,
|
||
'fonts.gstatic.com',
|
||
'fonts.googleapis.com',
|
||
'unpkg.com'
|
||
]
|
||
|
||
// The Util Function to hack URLs of intercepted requests
|
||
const getFixedUrl = (req) => {
|
||
var now = Date.now()
|
||
var url = new URL(req.url)
|
||
|
||
// 1. fixed http URL
|
||
// Just keep syncing with location.protocol
|
||
// fetch(httpURL) belongs to active mixed content.
|
||
// And fetch(httpRequest) is not supported yet.
|
||
url.protocol = self.location.protocol
|
||
|
||
// 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
|
||
if (url.hostname === self.location.hostname) {
|
||
url.search += (url.search ? '&' : '?') + 'cache-bust=' + now
|
||
}
|
||
return url.href
|
||
}
|
||
|
||
/**
|
||
* @Lifecycle Activate
|
||
* New one activated when old isnt being used.
|
||
*
|
||
* waitUntil(): activating ====> activated
|
||
*/
|
||
self.addEventListener('activate', event => {
|
||
event.waitUntil(self.clients.claim())
|
||
})
|
||
|
||
/**
|
||
* @Functional Fetch
|
||
* All network requests are being intercepted here.
|
||
*
|
||
* void respondWith(Promise<Response> r)
|
||
*/
|
||
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
|
||
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())
|
||
|
||
// 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)
|
||
.catch(_ => { /* eat any errors */ })
|
||
)
|
||
|
||
// Update the cache with the version we fetched (only for ok status)
|
||
event.waitUntil(
|
||
Promise.all([fetchedCopy, caches.open(RUNTIME)])
|
||
.then(([response, cache]) => response.ok && cache.put(event.request, response))
|
||
.catch(_ => { /* eat any errors */ })
|
||
)
|
||
}
|
||
})
|
||
```
|
||
|
||
## Registrieren
|
||
|
||
Jetzt registrieren wir die Funktion in der Datei `index.html`. Nur manche aktuellen Browser unterstützen die Funktion, wir müssen also prüfen:
|
||
|
||
*index.html*
|
||
|
||
```html
|
||
<script>
|
||
if (typeof navigator.serviceWorker !== 'undefined') {
|
||
navigator.serviceWorker.register('sw.js')
|
||
}
|
||
</script>
|
||
```
|
||
|
||
## Geniessen
|
||
|
||
Du kannst die Website jetzt veröffentlichen und Benutzer können sie dann vollständig offline verwenden, sobald sie einmal geladen wurde :ghost: Du kannst das jetzt ausprobieren, indem du deine Internetverbindung ausschaltest und diese Seite neu lädst.
|