PWA(progressive web application) —— 渐进式网络应用,让用户在离线环境也能有不错的用户体验
Service Work
服务工作线程
- 常驻内存运行
- 代理网络请求
- 依赖 HTTPS
启动
navigator.serviceWork.register(<scriptURL>, {scope: <scopeURL>})
.then(sw => console.log('sw', sw))
.catch(e => console.log('error', e))
Promise
“承诺”控制流
- 解决回调地狱
- async/await 语法同步化
- Service Work 的 API 风格
fetch
网络请求
- 比 XMLHttpRequest 更简洁
- Promise 风格
- 存在不足
不支持 abort 中断- 通过
AbortController
支持请求中断,详见 How to Cancel a Fetch Request
- 通过
不部分支持进度事件- 支持下载进度,详见 Fetch: Download progress
- 不支持上传进度
cache API
支持资源的缓存系统
- 缓存资源(css/scripts/image)
- 依赖 Service Work 代理网络请求
- 支持离线程序运行
使用
```javascript self.addEventListener(‘install’, evt => { // 拉取并缓存对应的资源 }) self.addEventListener(‘activate’, evt => { // 清除上一个 service 版本遗留的资源 }) self.addEventListener(‘fetch’, evt => { // 查找并返回缓存中的资源 })
<a name="tKFI6"></a>
## Notification API
消息推送
- 依赖用户授权
- 适合在 Service Work 中推送
<a name="i3G8q"></a>
### 使用
<a name="cca5592b"></a>
#### 查看推送权限
权限分为 'granted' 'default' 'denied'
```javascript
Notification.permission
请求权限
Notification.requestPermission()
.then(p => console.log('permission', p))
推送
页面
// 确保权限为 'granted' new Notification('Notification', { body: 'Life is fantastic!' })
Service Work
// 确保权限为 'granted' self.registration.showNotification('Notification', { body: 'Life is fantastic!' })