How to add more files to this service worker cache method

Hi guys,

I’ve been learning about service worker and I try to cache files to make my site works offline.
The example here works great so far: https://googlechrome.github.io/samples/service-worker/custom-offline-page/
However, it only works for caching one file. What if I want to cache more files like a separated js or css files and image files.
I tried to use an array and addAll method as seen in other tutorials and it isn’t worked. Most of those tutorial aren’t worked good like this.
Here’s the full code without comment:

const CACHE_VERSION = 1;
let CURRENT_CACHES = {
	offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'offline.php';

function createCacheBustedRequest(url) {
	let request = new Request(url, {cache: 'reload'});

	if ('cache' in request) {
		return request;
	}

	// If {cache: 'reload'} didn't have any effect, append a cache-busting URL parameter instead.
	let bustedUrl = new URL(url, self.location.href);
	bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
	return new Request(bustedUrl);
}

self.addEventListener('install', event => {
	event.waitUntil(
		fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
			return caches.open(CURRENT_CACHES.offline).then(function(cache) {
				return cache.put(OFFLINE_URL, response);
			});
		})
	);
});

self.addEventListener('activate', event => {
	let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
		return CURRENT_CACHES[key];
	});

	event.waitUntil(
		caches.keys().then(cacheNames => {
			return Promise.all(
				cacheNames.map(cacheName => {
					if (expectedCacheNames.indexOf(cacheName) === -1) {
						console.log('Deleting out of date cache:', cacheName);
						return caches.delete(cacheName);
					}
				})
			);
		})
	);
});

self.addEventListener('fetch', event => {
	if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
		console.log('Handling fetch event for', event.request.url);
		event.respondWith(
			fetch(event.request).catch(error => {
				console.log('Fetch failed; returning offline page instead.', error);
				return caches.match(OFFLINE_URL);
			})
		);
	}
});

Thank you,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.