[英]Is there a way to tell if you're getting cached data from the service worker?
[英]service worker: cached data again loads from server, fetch is not triggered
因此清單已被棄用,試圖在 express web 應用程序中實現服務工作者。 這是我的項目結構:
app.js
views >
login >
login.ejs
public >
lib
css
images
html
js
sw.js
在我的快遞應用程序中,我正在使用這樣的公用文件夾:
app.use("/static", express.static(path.join(__dirname, 'public')));
login.ejs 模板渲染 & 在 login.ejs 內部具有服務工作者加載代碼
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/static/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
並且注冊成功。
和 sw.js
const CACHE_NAME = 'v3'
// list of files
const URLS_TO_CACHE = [
"/static/images/favicon.ico",
"/static/lib/bootstrap/img/off.png",
"/static/lib/bootstrap/img/on.png",
"/static/html/help/lib/css/style.css",
"/static/lib/templates/login/account.js"
];
self.addEventListener("install", function (event) {
console.log("[Service Worker] install");
event.waitUntil(caches.open(CACHE_NAME).then(function (cache) {
console.log("[Service Worker] Caching app shell");
return cache.addAll(URLS_TO_CACHE);
})
.then(function () {
self.skipWaiting();
}));
});
self.addEventListener('activate', function (event) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if (key !== CACHE_NAME) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', e =>{
console.log("service worker : fetching");
e.respondWith(
fetch(e.request).catch(() => caches.match(e.request))
)
});
安裝和激活監聽器工作正常,並且 url 也被緩存到緩存存儲中。
當相同的應用程序重新加載或頁面導航時,不會觸發 fetch 並且永遠不會從服務工作者加載數據總是從服務器加載。
但是當我在不同的瀏覽器選項卡中嘗試時,例如: http://localhost:3000/static/lib/bootstrap/img/off.png
它的負載來自服務人員的獲取。
當我研究時,我了解了 scope,但在這里我希望我的 sw.js 文件已經在頂部 scope,
我的預期行為是:在每個頁面加載/導航緩存的 url 用於代替服務器調用,請為此提出任何解決方法
終於解決了 scope 問題,將 sw.js 文件從 static 移動到項目根目錄(與 app.js 並行)並像下面這樣使用,問題解決了。
app.use('/sw', express.static(path.join(__dirname, '/sw.js')));
並更改 login.ejs 如下
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.