Custom Expiration Logic (Client-Side)
Implements logic within the service worker itself to manage expiration based on timestamps or other criteria. Developers store timestamps or other expiration information alongside cached resources within the service worker.
Service Worker Implementation:
async function cacheAndStoreTimestamp(request, response) {
const cache = await caches.open('my-cache');
const timestamp = Date.now();
const responseWithTimestamp =
new Response(response.body,
{
...response.headers,
'X-Cache-Timestamp': timestamp
});
await cache.put(request, responseWithTimestamp);
}
async function handleFetch(event) {
const cachedResponse =
await caches.match(event.request);
if (cachedResponse) {
const cacheTimestamp =
cachedResponse.headers.get('X-Cache-Timestamp');
const isFresh =
// Implement logic based on
// timestamp and expiration duration
isFresh(cacheTimestamp, expirationTimeInMs);
if (isFresh) {
return cachedResponse;
}
}
return fetch(event.request);
}
function isFresh(cacheTimestamp, expirationTimeInMs) {
const now = Date.now();
const cachedTime = parseInt(cacheTimestamp);
return now - cachedTime < expirationTimeInMs;
}
Explanation of isFresh function:
- It takes the cached timestamp and expiration time in milliseconds as arguments.
- It calculates the difference between the current time (now) and the cached time (cachedTime).
- A cached response is considered fresh if the difference is less than the expiration time.
Output:
The service worker's behavior depends on the implemented logic.
If a fresh cached response exists (based on cache-control headers or custom logic), it's returned.
If the cached response is expired or not found, the service worker fetches new resources from the network.
How to Set an Expiration Date for Items in a Service Worker Cache using JavaScript?
Service workers empower web applications to cache resources for offline access and improved performance. However, outdated cached data can negatively impact user experience.
This article explores two effective strategies for setting expiration dates for cached items within a service worker using JavaScript, ensuring your application delivers fresh content.
Table of Content
- Cache-Control Headers
- Custom Expiration Logic
Contact Us