Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@onigetoc
Forked from benrobygreene/installer.js
Created February 26, 2023 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onigetoc/b56ed7a8aca0bafd9bdc832308ff49f6 to your computer and use it in GitHub Desktop.
Save onigetoc/b56ed7a8aca0bafd9bdc832308ff49f6 to your computer and use it in GitHub Desktop.
Service Workers
/**
* If there are service workers available to us, then on window load we can register our worker
*/
'serviceWorker' in navigator && window.addEventListener('load', () => {
navigator.serviceWorker.register('worker.js')
.then(() => {
// Registration was successful
console.log('ServiceWorker registration successful!');
}, (err) => {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
// Fires when the browser trys to fetch any asset
self.addEventListener('fetch', (event) => {
event.respondWith(
// check if the asset is one we are saving/watching
caches.match(event.request).then((eventRequest) => {
return eventRequest || fetch(event.request).then((response) => {
// try to open the cache, but fall back on the request if we can't open the cache
return caches.open(CACHE_NAME)
.then((cache) => {
// replace the request with the cache's content
cache.put(event.request, response.clone());
return response;
});
});
});
);
});
// This gets updated on new builds!
const CACHE_NAME = `Cache_${__SERVICE_WORKER_V__}`;
const urlsToCache = [
...
];
// Perform install steps of adding all defined assets to the cache
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache));
);
});
const webpack = require('webpack');
module.exports = {
// ...
plugins: [
// This is for auto updating the service worker version on builds
new webpack.DefinePlugin({
__SERVICE_WORKER_V__: Date.now()
})
],
// ...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment