【发布时间】:2021-01-08 13:51:20
【问题描述】:
我有这个 sw.js 的 pwa:
const info = "versione: 1.0.0 data: 07-01-2020 12:46";
const CACHE = "pwa-offline";
const pages = [
// some files
];
self.addEventListener("install", function (event) {
//console.log("Install Event processing");
self.skipWaiting();
event.waitUntil(
caches.open(CACHE).then(function (cache) {
//console.log("Cached offline page during install");
return cache.addAll(pages);
})
);
});
self.addEventListener("activate", (event) => {
});
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
event.respondWith(
fetch(event.request)
.then(function (response) {
return fromCache(event.request);
})
.catch(function (error) {
//console.log("Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
});
async function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
const cache = await caches.open(CACHE);
const matching = await cache.match(request);
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
}
async function updateCache(request, response) {
const cache = await caches.open(CACHE);
return cache.put(request, response);
}
和 index.html 里面有这段代码:
<script>
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./sw.js")//, {updateViaCache: 'none'})
.then(reg => {
//console.log("Registration successful", reg);
})
.catch(e =>
console.error("Error during service worker registration:", e)
);
} else {
console.warn("Service Worker is not supported");
}
</script>
我将 pwa 上传到 firebase 站点。当我更改 sw.js 时(例如更改 versionDate 的日期,在此站点 https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle 我读到:“如果您的服务工作者与浏览器已有的字节不同,则认为它已更新。(我们'重新扩展它以包括导入的脚本/模块。)") 然后我上传,我看到新的服务工作者已经改变了。但是当我在 sw.js 中进行第二次更改并上传时,sw.js 没有更改,所以我只能对 sw.js 进行更新,因此对整个站点进行更新(因为 sw.js 缓存了安装过程中的站点)。 如何随时更新我的网站?
更新:我看到问题出在桌面的 android 手机上没问题。
更新:现在它也适用于 android,但更新不是即时的。几个小时后我看到了更新。
【问题讨论】:
标签: service-worker