Updated ServiceWorker

This commit is contained in:
Erik Römmelt 2019-02-09 19:33:29 +01:00
parent 81da3b0057
commit 855dbf8ba7

View File

@ -1,167 +1,151 @@
'use strict'; 'use strict';
/* ================================== */
/* NOTE: Registration done in main.js */
/* ================================== */
// NOTE: CacheKey & FilesToCache Lists /* =================================== */
const cacheKey = 'omapp-'; /* NOTE: CacheKey & FilesToCache Lists */
const staticCacheKey = cacheKey + 's-v' + '1'; /* =================================== */
const dataCacheKey = casheKey + 'd-v' + '1'; const version = '1';
const staticFilesToCache = [ const appPrefix = 'ohmnews-';
'/', const staticCacheKey = appPrefix + 'static-v' + version;
'manifest.json', const dataCacheKey = appPrefix + 'content-data';
'index.html', var allCacheKey = [
'message.html', staticCacheKey,
'bookmark.js', dataCacheKey
'createMessage.js',
'files.js',
'home.js',
'main.js',
'profil.js',
'favicon.ico',
'img/th_nbg_ohmicon_amp.png',
'lib/jquery-3.3.1.min.js',
'lib/vue.js',
'lib/vue-router.js',
'style/style.css',
];
const dataFilesToCache = [
'',
]; ];
// NOTE: Registration done in main.js /* ================================== */
/* NOTE: Install: Save files to cache */
// NOTE: Install and activate: Populating cache /* ================================== */
// Install new service worker even when old version still in use. // Install new service worker even when old version still in use.
// Install happens only once a lifetime of a service worker. // Install happens only once a lifetime of a service worker.
self.addEventListener('install', function(event) { const cacheResources = async () => {
console.log('[ServiceWorker] Install'); const staticFilesToCache = [
'./',
'favicon.ico',
'index.html',
'main.js',
'manifest.json',
'font/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2',
'font/KFOlCnqEu92Fr1MmEU9fBBc4.woff2',
'font/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2',
'font/KFOlCnqEu92Fr1MmSU5fBBc4.woff2',
'font/KFOlCnqEu92Fr1MmSU5fChc4EsA.woff2',
'font/KFOlCnqEu92Fr1MmWUlfBBc4.woff2',
'font/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2',
'font/KFOmCnqEu92Fr1Mu4mxK.woff2',
'font/KFOmCnqEu92Fr1Mu7GxKOzY.woff2',
'img/launcher/launcher_app_icon_152.png',
'img/launcher/launcher_app_icon_167.png',
'img/launcher/launcher_app_icon_180.png',
'img/launcher/launcher_app_icon_192.png',
'img/launcher/launcher_app_icon_512.png',
'img/app_icon.png',
'img/launcher_app_icon.png',
'img/profil_icon.png',
'lib/bootstrap-font-and-icons.css',
'lib/bootstrap-material-design.js',
'lib/bootstrap-material-design.min.css',
'lib/jquery-3.3.1.min.js',
'lib/popper-1.12.6.js',
'lib/vue-router.js',
'lib/vue.js',
'routes/bookmark.js',
'routes/createMessage.js',
'routes/files.js',
'routes/home.js',
'routes/messageData.js',
'routes/msgCard.js',
'routes/profil.js',
'routes/profilCard.js',
'routes/profilData.js',
'style/style.css',
];
const dataFilesToCache = [];
const cacheStatic = await caches.open(staticCacheKey);
cacheStatic.addAll(staticFilesToCache);
console.log('[ServiceWorker] Cache static files.');
const cacheData = await caches.open(dataCacheKey);
cacheData.addAll(dataFilesToCache);
console.log('[ServiceWorker] Cache data files.');
return;
}
self.addEventListener('install', event => {
// don't wait // don't wait
self.skipWaiting(); self.skipWaiting();
// cache static files // cache static files
event.waitUntil( event.waitUntil(cacheResources())
caches.open(staticCacheKey).then(function(cache) { console.log('[ServiceWorker] Install');
console.log('[ServiceWorker] Cache static files.');
return cache.addAll(staticFilesToCache);
}),
caches.open(dataCacheKey).then(function(cache) {
console.log('[ServiceWorker] Cache data files.');
return cache.addAll(dataFilesToCache);
})
);
}); });
// NOTE: Activate structure and delete older cache versions /* ================================================================ */
// Activates new version of service worker. /* NOTE: Activate: new service worker and delete old cache versions */
/* ================================================================ */
// No fetch or pull is called before succesfull activate event. // No fetch or pull is called before succesfull activate event.
self.addEventListener('activate', function(event) { const cacheCleanUp = async () => {
clients.claim(); const cacheKeyList = await caches.keys();
var cacheWhitelist = [staticCacheKey, dataCacheKey]; const deletions = cacheKeyList
event.waitUntil( .filter(key => key.startsWith(appPrefix) && !allCacheKey.includes(key))
caches.keys().then(function(cacheKeyList) { .map(key => {
return Promise.all( caches.delete(key)
cacheKeyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
console.log('[ServiceWorker] Removing old cache', key); console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key); });
for (const success of deletions) {
await success;
} }
}) return;
); }
}).then(() => { self.addEventListener('activate', event => {
event.waitUntil(cacheCleanUp());
clients.claim();
console.log('[ServiceWorker] Activate'); console.log('[ServiceWorker] Activate');
})
);
// Shorten activation time for initial [ServiceWorker] call.
//return self.clients.claim();
}); });
/* ========================================= */
/* NOTE: Fetch: Update logic for cache files */
/* ========================================= */
// NOTE: Fetch structure // TODO: Setup fetching method self.addEventListener('fetch', event => {
self.addEventListener('fetch', function(event) { // Provide HTTPS URL for query data.
const dataUrl = ' localhost:8013/'; // Provide HTTPS URL for query data. const dataUrl = 'https://me.efi.th-nuernberg.de/om/';
// const url = new URL(event.request.url); // Parse the URL:
console.log('[ServiceWorker] Fetch', event.request.url); const requestURL = new URL(event.request.url);
//if (event.request.url.indexOf(dataUrl) > -1) {
/*
* When the request URL contains dataUrl, the app is asking for fresh
* data. In this case, the service worker always goes to the network
* and then caches the response. This is called
* the "Cache then network" strategy:
* https://jakearchibald.com/2014/offline-cookbook/#cache-then-network
*/
/*event.respondWith( // Start the network request as soon as possible.
caches.open(staticCacheKey).then(function(cache) { //const networkPromise = fetch('/data.json');
return fetch(event.request).then(function(response) {
cache.put(event.request.url, response.clone());
return response;
});
})
);
} else {
*/
/*
* The app is asking for app shell files. In this scenario the app uses the
* "Cache, falling back to the network" offline strategy:
* https://jakearchibald.com/2014/offline-cookbook/#cache-falling-back-to-network
*/
/*
// serve the cat SVG from the cache if the request is
// same-origin and the path is '/dog.svg'
if (url.origin == location.origin && url.pathname == '/dog.svg') {
event.respondWith(caches.match('/cat.svg'));
}
*/
event.respondWith( event.respondWith(
caches.match(event.request) caches.match(event.request)
.then(function(response) { .then(cachedResponse => {
if (response) { if (cachedResponse) {
return response; return cachedResponse;
} }
return fetch(event.request).then( console.log('[ServiceWorker] Fetch', requestURL.href);
function(response) { return fetch(event.request).then(response => {
// Check if we received a valid response // Check if we received a valid response
// - Ensure the response is valid. // - Ensure the response is valid.
// - Check the status is 200 on the response. // - Check the status is 200 on the response.
// - Make sure the response type is basic, which indicates that it's a request from our origin. // - Make sure the response type is basic, which indicates that it's a request from our origin.
// This means that requests to third party assets aren't cached as well. // This means that requests to third party assets aren't cached as well.
if(!response || response.status !== 200 || response.type !== 'basic') { if (!response || response.status !== 200 || response.type !== 'basic') {
return response; return response;
} }
// IMPORTANT: Clone the response. A response is a stream // We have to clone the response here because request bodies
// and because we want the browser to consume the response // can only be read once. Placing a response in the cache
// as well as the cache consuming the response, we need // counts as a read and so does the `res.json` call below.
// to clone it so we have two streams.
// - Reason: response is a stream and object can only consumed once
var responseToCache = response.clone(); var responseToCache = response.clone();
caches.open(staticCacheKey) caches.open(staticCacheKey).then(cache => {
.then(function(cache) {
cache.put(event.request, responseToCache); cache.put(event.request, responseToCache);
}); });
return response; return response;
} });
);
}) })
); );
//}
/*
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return caches.open(shellCacheKey).then(cache => {
return fetch(event.request).then(response => {
// Put a copy of the response in the runtime cache.
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})*/
}); });