PWA初探索

PWA简介

Progressive Web App, 简称 PWA,是提升 Web App 的体验的一种新方法,能给用户原生应用的体验。

PWA 本质上是 Web App,借助一些新技术也具备了 Native App 的一些特性,兼具 Web App 和 Native App 的优点。

实践

目录结构
  • index.html
  • manifest.json
  • sw.js
  • test.png

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./manifest.json" />
<title>PWA Demo</title>
</head>
<body>
<p>hello world</p>

<script>
if('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js', {scope: '/'})
.then(function(registration) {
console.log('serviceWorker registration successfull with scope: ', registration.scope);
})
.catch(err => {
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
</body>
</html>
manifest.json

PWA允许将站点添加到桌面,该功能实现依赖于 manifest.json。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"name": "PWA Demo",
"short_name": "PWA Demo",
"display": "standalone",
"start_url": "/",
"theme_color": "#8888ff",
"background_color": "#8888ff",
"icons": [
{
"src": "test.png",
"type": "image/png",
"sizes": "256x256",

}
]
}
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//安装
self.addEventListener('install', e => {
e.waitUntil(
//CacheStorage缓存
caches.open('my-test-cache-v1').then(cache => {
return cache.addAll([
'/',
'index.html',
'test.png'
]);
})
);
});

self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request).then(res => {
if(res) {
return res;
}

//service worker无返回,直接请求真实远程服务
var request = e.request.clone();
return fetch(request).then(httpRes => {
if(!httpRes || httpRes.status !== 200) {
return httpRes;
}

//请求成功,将请求缓存
var responseClone = httpRes.clone();
caches.open('my-test-cache-v1').then(cache => {
cache.put(e.request, responseClone);
});

return httpRes;
});
})
);
});

self.addEventListener('activate', e => {
event.waitUntil(
Promise.all([
self.clients.claim(),
caches.keys().then(cacheList => {
return Promise.all(
cacheList.map(cacheName => {
if(cacheName !== 'my-test-cache-v1') {
return caches.delete(cacheName);
}
})
);
})
])
);
});

启动本地 http server

用python在根目录下启动

1
2
3
4
5
// python 3
python -m http.server 8080

//python 2
python -m SimpleHTTPServer 8080

查看

localhost

localhost

可以看到成功注册了Service Worker。

cache

cache

cache中成功缓存了资源。

network

network

可以看到网络静态资源从 Service Worker中获取。

参考资料

PWA文档

PWA 入门: 写个非常简单的 PWA 页面