To write a service worker that returns cached HTML files, you can use the caches.match() method to check if the requested resource is already in the cache, and if it is, return the cached response. Here is an example of how you can use this method to cache and return HTML files:
self.addEventListener(`fetch`, function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
// If a cached response is found, return it
if (response) {
return response;
}
// Otherwise, fetch the resource from the network
return fetch(event.request).then(function(response) {
// Clone the response so it can be cached
var responseClone = response.clone();
// Cache the response
caches.open(`my-cache`).then(function(cache) {
cache.put(event.request, responseClone);
});
// Return the original response
return response;
});
})
);
});
In this example, the fetch event listener intercepts all network requests made by the page, and uses caches.match() to check if a cached response is available. If a cached response is found, it is returned using return response.
If no cached response is found, the service worker falls back to fetching the resource from the network using return fetch(event.request). Once the response is obtained from the network, it is cloned using var responseClone = response.clone();. This is necessary because the original response can only be consumed once, so we need to create a copy of it to cache.
The response is then cached using the cache.put() method, and the original response is returned using return response;. This allows the page to receive the original response, while the cached copy is stored for future requests.
Note that in this example, the cache name used is `my-cache`. You can use any name you like for your cache. Additionally, if you only want to cache HTML files, you can modify the if statement to check if the requested resource has a MIME type of `text/html`. Here is an example:
self.addEventListener(`fetch`, function(event) {
if (event.request.headers.get(`Accept`).includes(`text/html`)) {
event.respondWith(
caches.match(event.request).then(function(response) {
// If a cached response is found, return it
if (response) {
return response;
}
// Otherwise, fetch the resource from the network
return fetch(event.request).then(function(response) {
// Clone the response so it can be cached
var responseClone = response.clone();
// Cache the response
caches.open(`my-cache`).then(function(cache) {
cache.put(event.request, responseClone);
});
// Return the original response
return response;
});
})
);
}
});
In this modified example, the if statement checks if the requested resource has a MIME type of `text/html`. If it does not, the service worker does not intercept the request, and the default network behavior is used. If it does, the service worker behaves as described above, caching and returning the response if it is available in the cache.
Be the first to comment