![](/img/trans.png)
[英]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.