This is a collection of ES2017 classes (so a transpiler is needed, webpack is used here with babel and the env preset) that utilize Service Workers to add offline support for a site. This example should work for WordPress sites as well
Because DOMParser
is not included in Service Workers, you will need to install the npm package xmldom
npm install xmldom --save-dev
This resulting links are meant to be added to the service worker in order to be cached in a fashion that keeps the most up to date data cached, so:
- Fetch the list on the network
- Override the cache with the new list
- Cache all the links in the list
- Fetch the list in the cache
- Cache all the links in the list
Please note that there must be an offline.js
in the webroot of the project, but it is fine to import a script to it (so a compiled script) via importScripts inside a Service worker, here's an example with webpack and gulp build tools
if('serviceWorker' in navigator && window.location.protocol === 'https:'){
try {
navigator.serviceWorker
.register('/offline.js')
.then(() => {
console.log('Service Worker Registered');
});
} catch(e) {
console.log(e);
}
}
fetch('<url/to/assets>/webpack/manifest.json')
.then(data => data.json())
.then(data => {
importScripts(data['offline.js']);
});