Service Worker的基本使用
環境準備
安裝http-server
npm install -g http-server
準備index.html
<head>
? <title>Minimal PWA</title>
? <meta name="viewport" content="width=device-width, user-scalable=no" />
? <link rel="manifest" href="manifest.json" />
? <link rel="stylesheet" type="text/css" href="main.css">
? <link rel="icon" href="/e.png" type="image/png" />
</head>
<body>
? <div class="revision">Revision 8</div>
? <img src="pwa-fonts.png">
? <div class="main-text">
? ? Minimal PWA, open Console for more!
? </div>
? <div class="network-message">
? ? Network:
? ? <span id="network-status" class="">Good</span>
? </div>
? <script type="text/javascript">
? ? if (navigator.serviceWorker != null) {
? ? ? navigator.serviceWorker.register('sw.js')
? ? ? .then(function(registration) {
? ? ? ? console.log('Registered events at scope: ', registration.scope);
? ? ? });
? ? }
? ? fetch('./data.json')
? ? var statusEl = document.querySelector('#network-status')
? ? if (!navigator.onLine) {
? ? ? statusEl.classList = ['is-offline']
? ? ? statusEl.innerText = 'Offline'
? ? }
? </script>
</body>
準備css文件main.css
body {
? display: flex;
? flex-direction: column;
? justify-content: center;
? align-items: center;
? font-family: Helvetica Neue;
? font-weight: 200;
? font-size: 20px;
? background-color: #313131;
? background-image: radial-gradient(ellipse farthest-corner at 45px 45px ,
? ? ? ? ? ? ? ? ? ? ? ? hsla(0,80%,100%,0.32) 0%,
? ? ? ? ? ? ? ? ? ? ? ? hsla(0,80%,80%,0.16) 60%,
? ? ? ? ? ? ? ? ? ? ? ? hsla(0,80%,80%,0) 95%);
? color: #ccc;
}
.main-text {
? white-space: nowrap;
}
img {
? width: auto;
? max-width: 80%;
}
.revision {
? font-weight: 200;
? position: fixed;
? top: 32px;
? left: 32px;
}
.network-message {
? font-weight: 200;
? position: fixed;
? bottom: 32px;
? right: 32px;
}
準備manifest.json, 用于生成桌面快捷方式
{
? "name": "Minimal PWA",
? "short_name": "PWA Demo",
? "display": "standalone",
? "start_url": "/",
? "theme_color": "#313131",
? "background_color": "#313131",
? "icons": [
? ? {
? ? ? "src": "e.png",
? ? ? "sizes": "256x256",
? ? ? "type": "image/png"
? ? }
? ]
}
準備service worker文件sw.js
console.log('Script loaded!')
//緩存倉庫名字
var cacheStorageKey = 'minimal-pwa-8' ?
//需要緩存的文件
var cacheList = [
? '/',
? "index.html",
? "main.css",
? "e.png",
? "pwa-fonts.png"
]
//處理安裝事件
self.addEventListener('install', function(e) {
? console.log('Cache event!')
? e.waitUntil(
? ? caches.open(cacheStorageKey).then(function(cache) {
? ? ? console.log('Adding to Cache:', cacheList)
? ? ? return cache.addAll(cacheList)
? ? }).then(function() {
? ? ? console.log('Skip waiting!')
? ? ? return self.skipWaiting()
? ? })
? )
})
//處理activate事件
self.addEventListener('activate', function(e) {
? console.log('Activate event')
? e.waitUntil(
? ? Promise.all(
? ? ? caches.keys().then(cacheNames => {
? ? ? ? return cacheNames.map(name => {
? ? ? ? ? if (name !== cacheStorageKey) {
? ? ? ? ? ? return caches.delete(name)
? ? ? ? ? }
? ? ? ? })
? ? ? })
? ? ).then(() => {
? ? ? console.log('Clients claims.')
? ? ? return self.clients.claim()
? ? })
? )
})
//處理fetch事件
self.addEventListener('fetch', function(e) {
? // console.log('Fetch event:', e.request.url)
? e.respondWith(
? ? caches.match(e.request).then(function(response) {
? ? ? if (response != null) {
? ? ? ? console.log('Using cache for:', e.request.url)
? ? ? ? return response
? ? ? }
? ? ? console.log('Fallback to fetch:', e.request.url)
? ? ? return fetch(e.request.url)
? ? })
? )
})
運行http-server
http-server -p 8000 -c-1
首次訪問從網絡下載頁面
停掉http-server,一樣可以正常訪問
通過chrome dev tools查看service workers
查看Cache Storage
移動端訪問,可以通過ngrok工具來完成
加上AppShell就是一個完整的PWA應用。
參考資料
https://zhuanlan.zhihu.com/p/25459319
https://kymjs.com/code/2017/02/15/01/
https://kymjs.com/code/2017/02/18/01/
https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker
https://developers.google.com/web/fundamentals/getting-started/codelabs/your-first-pwapp/?hl=zh-cn#progressive_web_app
總結
以上是生活随笔為你收集整理的Service Worker的基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下用GDB调试程序崩溃错误
- 下一篇: Docker for windows 1