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