是否可以在Angular中添加手动创建的Service Worker
而不是配置JSON?
我想实现自己的自定义代码
答案 0 :(得分:0)
您可以通过这样创建sw.js文件
var cacheName = "your cache name";
self.addEventListener("install", event => {
event.waitUntil(
caches
.open(cacheName)
.then(cache =>
cache.addAll([
])
).then(() => self.skipWaiting())
);
});
//Removing outdated caches
self.addEventListener("activate", function (event) {
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames
.filter(function (cacheName) {
return true;
})
.map(function (cacheName) {
return caches.delete(cacheName);
})
);
}).then(() => self.clients.claim())
);
});
// Cache any new resources as they are fetched
self.addEventListener("fetch", function (event) {
});
然后在您的app.component.ts中放置以下代码
public ngOnInit() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./sw.js")
.then(registration => {
// Registration was successful
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope
);
})
.catch(err => {
// registration failed :(
console.log("ServiceWorker registration failed: ", err);
});
}
如有任何疑问,请告诉我