环境准备
安装http-server
npm install -g http-server
准备index.html
准备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