Cache-only Strategy for Static Assets
A simple example on how to implement a cache-only strategy for certain static assets that don't need to be updated frequently, such as CSS, JavaScript, or images.
// Register the service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
console.log('Service Worker Registered with scope:', registration.scope);
})
.catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
This code checks if the current browser supports service workers and then registers a service worker from a file named 'service-worker.js'. The registration process is logged to the console, both on success and on failure.
// Cache name
var CACHE_NAME = 'static-cache-v1';
// Files to cache
var STATIC_FILES = [
'/css/styles.css',
'/js/app.js',
'/images/logo.png'
// Add more static assets here
];
This piece of code initializes the name of the cache and an array containing the URLs of the static assets that will be stored in the cache.
// Service worker installation
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(STATIC_FILES);
})
);
});
This code handles the 'install' event for the service worker and calls `caches.open` to create a new cache with the name provided. After opening the cache, it adds all the static files to the cache by using the `addAll` method.
// Cache-only strategy for fetching static assets
self.addEventListener('fetch', function(event) {
if (STATIC_FILES.includes(new URL(event.request.url).pathname)) {
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// If the file is not cached, respond with a fetch from the network
return fetch(event.request);
})
);
}
});
This section of code listens for the 'fetch' event and applies a cache-only strategy to the static files listed in the `STATIC_FILES` array. For each fetch event, it checks if the requested file is one of our static assets, and if so, it tries to match it in the cache. If a cached version is found, it's returned immediately, otherwise, a network request is made as a fallback.