当前位置:网站首页>PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
PWA 踩坑 - 第一次加载页面后无法获取CacheStorage某些资源
2022-08-02 06:20:00 【JA+】
第一次加载Service Worker后,脱机再刷新,无法获取CacheStorage某些缓存的资源
对于很多网上的例子,监听fetch,并使用:caches.match获取缓存数据时
self.addEventListener('fetch', function (e) {
e.respondWith(
caches.match(e.request).then(res => {
...
在第一次挂载service worker时,我们使用cache.addAll()来将cacheList中指定路径的资源转移到缓存中。
const cacheList = ['./index.html',...]
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName)
.then(cache => {
return cache.addAll(cacheList);
})
.then(() => self.skipWaiting()),
);
});
问题与步骤
- 手动清除Service Worker,及caches缓存。
- 第一次加载页面后,马上脱机,然后再刷新。
- caches.match(e.request) ,一些特殊的资源会返回undefined,也就是找不到。
- 控制台查看缓存是有数据的。
- 联网状态下,刷新一次后,再脱机,则缓存资源能正常获取。
这个可以理解,因为这次刷新是在Service Worker生效的条件下。 那么网页中的资源请求都会被Service Worker 的fetch事件拦截,并以e.request 为key添加到cache缓存中。
调查
获取缓存失败的资源的特征:
- html 页面中<script type="module" >的资源
- css 中通过@font-face 引入的字体文件(.ttf) (验证了background:url引入的图片没有问题)
因此初步得出结论:
以上形式的资源,不能通过caches.match(Response) 的形式获取——由cache.addAll(cacheList) 缓存的数据
解决方案
caches.match(e.request.url),传入静态资源的url,可正常获取缓存数据。
猜测原因
可能是与这些资源第一次缓存时,存入的CacheStorage的 key不匹配导致的。
因为第一次进入的缓存是通过 cache.addAll 缓存,其缓存到cache的key为何值不清楚,导致二次脱机刷新时获取不到资源。而实际上已经有缓存。
截至写这篇文章时(2022-07-27)时,MDN(CacheStorage)上依旧为实验性。
根据CacheStorage.match(request, options) MDN 文档,其方法有第二个参数,options,它可以一定程度控制match的匹配规则。
从options.ignoreSearch 看出,匹配规则中会判断同一个url的参数是否相同。(这并不是原因)
未实际查明原因。
样本较少,若有错误或补充,敬请指出更正。
边栏推荐
猜你喜欢
typescript ‘props‘ is declared but its value is never read 解决办法
aTrust项目的相关操作与分享
(Notes are not completed) [Graph Theory] Traversal of graphs
Nodejs installation tutorial
MySQL Advanced - MVCC (ultra-detailed finishing)
(Part of it is not understood, and the notes are not completed) [Graph Theory] Difference Constraints
解决:- SPY: No data found for this date range, symbol may be delisted报错
nacos源码启动找不到istio包
8/1 思维+扩展欧几里得+树上dp
CAT1 4G+Ethernet development board Tencent cloud mobile phone WeChat applet display temperature and delivery control
随机推荐
Kind of weird!Access the destination URL, the host can container but not
Servlet
两篇不错的php debug教程
交换部分 VLAN
At age 94, pioneer Turing award winner, computational complexity theory, Juris Hartmanis, died
MySQL Advanced Statements (1)
PMP新考纲通关秘籍,告别抓瞎
数据库概论-MySQL的数据表的基本操作
Neo4j 中文开发者月刊 - 202207期
Xgboost报错ValueError:无效的形状:标签(1650 2)
暑期总结(三)
The stock price has repeatedly hit new lows, and the real estate SaaS giant is in trouble. How should Mingyuan Cloud transform and save itself?
pointer arithmetic in c language
Detailed explanation of 9 common reasons for MySQL index failure
chrome plugin development guide
实例029:反向输出
Toolbox App 1.25 New Features at a Glance | Version Update
How does abaqus quickly import the assembly of other cae files?
typescript 'props' is declared but its value is never read solution
交换网络----三种生成树协议