0
我用针线2.0.0服务工作者,以及一些网页,我现在用的是workboxSW.strategies.staleWhileRevalidate()的缓存策略:后处理网页内容与staleWhileRevalidate
const customFilter = {
cachedResponseWillBeUsed: function (input) {
try {
console.log('cacheResponseWillBeUsed for : ' + input.request.url);
// modify the response body here
} catch (e) {
console.error(e);
}
return input.cachedResponse;
},
requestWillFetch: function (input) {
try {
console.log('requestWillFetch for ' + input.request.url);
} catch (e) {
console.error(e);
}
return input.request;
},
fetchDidFail: function (input) {
console.log('A fetch request for ' + input.request.url + ' failed.');
}
}
const cachingStrategy = workboxSW.strategies.staleWhileRevalidate({
plugins: [
customFilter
]
});
workboxSW.router.registerRoute(
new RegExp('\/(.*)/suffix/?$'),
cachingStrategy
);
也进展顺利,并我可以更新从缓存获取的响应式响应。但我想要动态修改所有响应,包括第一次从网络获得响应(我必须在其中插入一些JavaScript)。
从我的测试中,cachedResponseWillBeUsed只允许从缓存(按照方法名称)后处理响应,但我还没有找到一种方法来获得对网络响应的访问(但仍然正常地使用staleWhileRevalidate策略)。
有什么建议吗?
非常感谢
这正是我最终做的(尽管花了一点时间才弄清楚)。 – Weeblr
对不起,快速输入。事实证明,使用cachedResponseWillBeUsed来修改响应并不是一个好主意。如果这样做,则不能再使用WorkBox的cacheExpiration选项,因为只能注册一个cachedResponseWillBeUsed方法。如此专门的方法来过滤响应确实是一个好主意。 – Weeblr