ServiceWork 缓存
category
Web
date
Jan 4, 2023
icon
slug
servicework-cache
status
Published
summary
tags
ServiceWork
JavaScript
type
Post
还算完整的 Service Worker Cache 示例
目录结构
基本结构用法
注册serviceWorker
serviceWorker.js
- self.skipWaiting()
表示强制当前处在 waiting 状态的 Service Worker 进入 activate 状态
- event.waitUntil()
传入一个 Promise 为参数,等到该 Promise 为 resolve 状态为止。
- self.clients.claim()
在 activate 事件回调中执行该方法表示取得页面的控制权, 这样之后打开页面都会使用版本更新的缓存。旧的 Service Worker 脚本不再控制着页面,之后会被停止。
基本 ServiceWorker Cache 构造
用 async/await 改造
五种缓存策略
- cachefirst 缓存优先
- cacheonly 仅缓存
- networkfirst 网络优先
- networkonly 仅网络
- StaleWhileRevalidate 从缓存取,用网络数据更新缓存