image.png
PWA(progressive web application) —— 渐进式网络应用,让用户在离线环境也能有不错的用户体验

Service Work

服务工作线程

  • 常驻内存运行
  • 代理网络请求
  • 依赖 HTTPS

    启动

    1. navigator.serviceWork.register(<scriptURL>, {scope: <scopeURL>})
    2. .then(sw => console.log('sw', sw))
    3. .catch(e => console.log('error', e))

Promise

“承诺”控制流

  • 解决回调地狱
  • async/await 语法同步化
  • Service Work 的 API 风格

fetch

网络请求

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!'
    })
    

实践 PWA

参考