service worker cache workbox code example

Example 1: workbox

// workbox webpack config

new GenerateSW({
			swDest: resolve(process.cwd(), 'build/service-worker.js'),
			runtimeCaching: [
				{
					handler: 'StaleWhileRevalidate',
					urlPattern: /\.(?:js|css|html)$/,
					options: {
						cacheName: 'static-assets-cache',
						cacheableResponse: {
							statuses: [0, 200]
						},
						expiration: {
							maxEntries: 100,
							maxAgeSeconds: 24 * 60 * 60 * 60
						}
					}
				},
				{
					handler: 'CacheFirst',
					urlPattern: /\.(?:jp?g|png|svg|gif|raw|webp)$/,
					options: {
						cacheName: 'images-assets-cache',
						cacheableResponse: {
							statuses: [200]
						},
						expiration: {
							maxEntries: 100,
							maxAgeSeconds: 24 * 60 * 60 * 180
						}
					}
				},
				{
					handler: 'CacheFirst',
					urlPattern: /\.(?:woff|woff2|eot|ttf|otf)$/,
					options: {
						cacheName: 'fonts-assets-cache',
						cacheableResponse: {
							statuses: [200]
						},
						expiration: {
							maxEntries: 100,
							maxAgeSeconds: 24 * 60 * 60 * 180
						}
					}
				}
			],
			clientsClaim: true,
			skipWaiting: true,
			cleanupOutdatedCaches: true
		}),

Example 2: workbox

//workbox GENERATE SW CONFIG
const path = require('path');

module.exports = {
	swDest: path.resolve(process.cwd(), 'src/serviceWorker.js'),
	globDirectory: process.cwd(),
	globPatterns: ['**/*.{js, css, html}'],
	globIgnores: [
	  'node_modules/**/*',
	  '**/gsw-wb.config.js',
	  '**/gij-wb.config.js'
	],
	runtimeCaching: [{
		 method: 'GET',
		 urlPattern: /\.(?:png|jpe?g|gif|svg)$/,
		 handler: "CacheFirst",
		 options: {
		 	cacheName: "images-assets",
		 	cacheableResponse: {
		 		statuses: [0, 200]
		 	},
		 	expiration: {
		 		maxEntries: 100,
		 		maxAgeSeconds: 24 * 60 * 60 * 7
		 	},
		 }
	}],
	clientsClaim: true,
	skipWaiting: true,
	cleanupOutdatedCaches: true,
	maximumFileSizeToCacheInBytes: 1572864
}