我正在使用服务工作者,我有以下代码
self.addEventListener('fetch', function (event) {
const url = new URL(event.request.url)
if (event.request.mode == "navigate") {
const fetchData = fetch(event.request).catch(function () {
//console.log("errr")
return caches.match("/core/index.php/offline_controlador/index")
});
event.respondWith(fetchData)
return;
}
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
});
当我尝试从缓存中获取这些文件时,它不起作用,但是当我将代码更改为
event.respondWith(
caches.match(event.request.url).then(function(response) {
return response || fetch(event.request);
})
);
而不是
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
它完美地工作
缓存存储 API 规范的相关部分是 5.4.2。(虽然这适用于Cache
对象的matchAll()
方法,但当你做caches.match()
时,这就是最终被称为"引擎盖下"的原因。
与您的问题特别相关的是第 2 步:
如果未省略可选参数请求,则:
如果
request
是Request
对象,则:
将
r
设置为request
的请求。如果
r
的方法不是GET
并且options.ignoreMethod
是假的,则返回 承诺使用空数组解析。否则,如果请求是字符串,则:
- 将
r
设置为调用初始结果的关联请求Request
的值作为构造函数,request
作为其参数。如果这个 抛出异常,返回一个被该异常拒绝的承诺。
总而言之,最大的区别是,如果Request
具有'GET'
以外的其他内容method
,则传入Request
对象作为第一个参数可能会导致match()
失败。也许这就是你碰到的。
除此之外,这两种方法应该基本相同,尽管传入Request
效率略高,因为浏览器不必基于字符串隐式创建Request
对象。