Skip to content

Instantly share code, notes, and snippets.

@zeraphie
Last active January 8, 2018 18:09
Show Gist options
  • Save zeraphie/f4270c5b6beb14fb1aaf23837c5408fd to your computer and use it in GitHub Desktop.
Save zeraphie/f4270c5b6beb14fb1aaf23837c5408fd to your computer and use it in GitHub Desktop.
Service Worker

Service Workers

Below is some boilerplate for using service workers inside a project so that a web application can still run to some degree in an offline environment

  • register-service-worker.js would be loaded into your normal javascript
  • service-worker.js would be on it's own in the directory you wish to run the service worker inside (urls should reflect this)
  • Things in <> brackets will need to be replaced by their relevant information

Note: Service Workers can only be run in an SSL secured environment

Note: Service Workers have a poor support at the moment, but may have greater support in the future


Here's the demo that can be used offline https://alberon.gitlab.io/service-workers-demo/

Date: 8th January 2018

if('serviceWorker' in navigator){
let prefix = '';
// Fix for gitlab pages
if(window.location.origin.indexOf('<namespace>.gitlab.io') > -1){
prefix = '/<project>';
}
navigator.serviceWorker
.register(`${prefix}/service-worker.js`)
.then(function () {
console.log('Service Worker Registered');
});
}
/*==============================================================================
Config variables
==============================================================================*/
const cacheName = '<chosen cache name>';
const dataCacheName = `data-${cacheName}`;
/*==============================================================================
Files to cache
==============================================================================*/
let prefix = '';
// Fix for gitlab pages
if(self.location.origin.indexOf('<namespace>.gitlab.io') > -1){
prefix = '/<project>';
}
let filesToCache = [
`${prefix}/`,
`${prefix}/build/js/master.js`,
`${prefix}/build/styles/master.css`,
];
/*==============================================================================
On installing the service worker, open the cache and add all the files to the
cache
==============================================================================*/
self.addEventListener('install', e => {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(cache => {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
/*==============================================================================
On activating the service worker, remove old caches
==============================================================================*/
self.addEventListener('activate', e => {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(keyList => {
return Promise.all(keyList.map(key => {
if(key !== cacheName && key !== dataCacheName){
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
/*==============================================================================
Use the cache then network strategy to load the resource
==============================================================================*/
self.addEventListener('fetch', e => {
/*--------------------------------------
Guard against extensions
--------------------------------------*/
if(e.request.url.indexOf(self.location.origin) === -1){
return;
}
console.log('[ServiceWorker] Fetch', e.request.url);
e.respondWith(
caches.open(dataCacheName).then(cache => {
return fetch(e.request).then(response => {
cache.put(e.request.url, response.clone());
return response;
});
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment