问题
Am new to service worker. I just want to know how the service worker handling the Data changes.
For example, I have configured my data group in and set strategy
to "performance"
so that Service worker will always look first in Cache. That means any time the Registered URL in hit service worker will look in the cache first. Suppose the response has some changes ( data in database got changed ) will the response will update or still, it will take from the cache.
I searched quite a bit in net I didn't get a satisfying answer. if anybody can please help me
Cofiguration
"dataGroups":[
{
"name":"task-user-api",
"urls":["/tasks","/users"],
"cacheConfig":
{
"strategy" : "performance",
"maxSize":20,
"maxAge":"1h",
"timeout":"5s"
}
}
]
回答1:
After few more hours of search, I found the answer to it, There are different type of caching available
a. Network or cache - Serve content from the network but include a timeout to fall back to cached data if the answer from the network doesn’t arrive on time.
b. Cache only -- Add static content during the installation of the service worker and use the cache to retrieve it whether the network is available or not.
c. Cache and Update -- Serve the content from the cache and also perform a network request to get fresh data to update the cache entry ensuring next time the user visits the page they will see up to date content.
d. Cache update and refresh -- Serve the content from the cache but at the same time, perform a network request to update the cache entry and inform the UI about new up to date content.
e. Embedded fallback -- Embed fallback content and serve it in case of a failure while requesting resources.
You can read more and get code for each implimentation from here
Complete code to get the Caching and alert on UI if anything changed on server
Service-worker.js
var cacheName = 'cache-update-and-refresh';;
var cacheFiles = [
'./',
// list all the assests you want to list
]
self.addEventListener('install', function (e) {
console.log("[serviceWorker] installed")
e.waitUntil(
caches.open('default-cache').then(function (cache) {
return cache.addAll(cacheFiles)
}).then(function () {
return self.skipWaiting();
}));
console.log("[serviceWorker] Cached")
})
self.addEventListener('activate', (event) => {
console.info('Event: Activate');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) { //cacheName = 'cache-v1'
return caches.delete(cache); //Deleting the cache
}
})
);
})
);
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
return response || fetch(event.request);
})
);
event.waitUntil(
update(event.request)
.then(function (response) {
caches.open(cacheName).then(function (cache) {
caches.match(event.request).then(function (cacheresponse) {
if (cacheresponse.headers.get("ETag") !== response.headers.get("ETag")) {
console.log('[ServiceWorker]' + response.url + ' - Cache' + cacheresponse.headers.get("ETag") + "- real" + response.headers.get("ETag"));
cache.put(event.request, response.clone()).then(function () {
refresh(event.request, response);
});
}
});
});
})
)
});
function fromCache(request) {
return caches.open(cacheName).then(function (cache) {
return cache.match(request);
});
}
function update(request) {
return caches.open(cacheName).then(function (cache) {
return fetch(request).then(function (response) {
return response;
});
});
}
function refresh(req, response) {
return self.clients.matchAll().then(function (clients) {
clients.forEach(function (client) {
var message = {
type: 'refresh',
url: response,
eTag: response.headers.get('ETag')
};
client.postMessage(JSON.stringify(message));
});
});
}
in Index.html
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js', { scope: './' })
.then(function (registration) {
console.log("Service worker registered", registration)
})
.catch(function (err) {
console.log("Service Worker Failes to Register", err)
})
navigator.serviceWorker.addEventListener('message', function (event) {
document.getElementById("cache-generic-msg").style.display = "block";
console.log("Got reply from service worker: " + event.data);
});
}
Sequence diagram
来源:https://stackoverflow.com/questions/49639114/how-api-is-getting-cached-effectively-using-service-worker-in-angular-5-using-a