Example 1: service worker.js
if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('/sw.js').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed :( console.log('ServiceWorker registration failed: ', err); }); });}
Example 2: 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 3: 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
}