Cache-Control Headers (Server-Side Configuration)
Relies on server configuration to instruct the service worker on caching duration. The server sends cache-control headers with responses, specifying how long to cache resources. Common directives include:
- max-age: Maximum duration (in seconds) a resource can be cached.
- expires: Absolute expiration date for the resource.
Syntax:
const express = require('express');
const app = express();
app.get('/my-resource', (req, res) => {
res.setHeader('Cache-Control', 'max-age=3600'); // Cache for 1 hour
res.sendFile('path/to/my-resource.js');
});
app.listen(3000, () => console.log('Server listening on port 3000'));
Service Worker Implementation:
The service worker intercepts requests and checks cached responses cache-control headers for freshness.
Example:
async function handleFetch(event) {
const response = await caches.match(event.request);
if (response) {
const cacheHeaders =
response.headers.get('Cache-Control');
if (isFresh(cacheHeaders)) {
return response;
}
}
return fetch(event.request);
}
async function isFresh(cacheHeaders) {
// Implement logic to parse cache-control
// headers and determine freshness
// This is a simplified example, assuming
// presence of a 'max-age' directive
const maxAge =
parseInt(cacheHeaders.match(/max-age=(\d+)/)?.[1]);
if (maxAge) {
const now = Date.now();
const responseTime =
parseInt(response.headers.get('Date'));
// Assuming responseTime is available
const age = now - responseTime;
return age < maxAge * 1000;
// Convert maxAge seconds to milliseconds
}
return false;
// Default to not fresh if max-age not found
}
Explanation of isFresh function :
- The isFresh function now attempts to parse the cacheHeaders for the max-age directive using a regular expression.
- It retrieves the response time from the response.headers (assuming it’s available) and calculates the age of the cached response.
- It compares the age with the max-age converted to milliseconds and returns true if fresh, false otherwise.
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