[英]How to update the cached files in my service worker every 30 minutes?
我有這個服務人員:
//IMPORT POLYFILL
importScripts('cache-polyfill.js');
//INSTALL
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('stock_item_balance_v1').then(function(cache) {
return cache.addAll([
'/app/offline_content/purchase/stock_items/stock_items_balance.php',
'/app/offline_content/purchase/stock_items/js/stock_items_balance.js'
]);
})
);
});
//FETCH (FETCH IS WHEN YOU CHECK FOR INTERNET)
self.addEventListener('fetch', function(event) {
//console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
在“stock_items_balance.php”中,我從我的數據庫中獲取數據。 因此,我想每 30 分鍾更新一次緩存頁面並重新加載 window。
所以首先我有一個檢查互聯網連接的腳本。
如果為真,我想清理/更新緩存並重新加載頁面。
我怎樣才能做到這一點?
//INTERVAL
setInterval(function(){
//CLEAN/UPDATE CACHED FILES
serviceworker.update(); // ???
//RELOAD PAGE
window.location.reload();
}, 180000);
(我認為您有一個更大的問題,即您所描述的方法是否真的會為您的用戶提供良好的、可預測的、可離線體驗,但我將只關注您提出的實際技術問題。)
首先,您應該記住,可以為同一個 URL 打開多個選項卡,如果您這樣做,您的更新代碼可能會運行多次。 此答案中的代碼在異步緩存更新完成后,從服務工作者內部為您處理“重新加載”步驟,方法是獲取服務工作者的所有活動客戶端的列表並告訴每個客戶端導航到當前 URL (這實際上是重新加載)。
// Additions to your service worker code:
self.addEventListener('message', (event) => {
// Optional: if you need to potentially send different
// messages, use a different identifier for each.
if (event.data === 'update') {
event.waitUntil((async () => {
// TODO: Move these URLs and cache names into constants.
const cache = await caches.open('stock_item_balance_v1');
await cache.addAll([
'/app/offline_content/purchase/stock_items/stock_items_balance.php',
'/app/offline_content/purchase/stock_items/js/stock_items_balance.js'
]);
const windowClients = await clients.matchAll();
for (const windowClient of windowClients) {
// Optional: check windowClient.url first and
// only call navigate() if it's the URL for one
// specific page.
windowClient.navigate(windowClient.url);
}
})());
}
});
// Additions to your window/page code:
setInterval(() => {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage('update');
}
}, 180000);
緩存存儲 API 可從服務工作者內部和頁面的window
scope 內部獲得。 通常我建議人們做的是從window
上下文中打開相同的緩存,並調用cache.add()
以使用來自網絡的最新更新緩存條目。 但是,從window
上下文調用cache.add()
將導致網絡請求被您的fetch
處理程序攔截,此時您的響應實際上不會來自網絡。 通過從服務工作者內部調用cache.add()
,您可以保證生成的網絡請求不會觸發您的fetch
處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.