From 660a1947cc842265c3540752b40f5637694e6193 Mon Sep 17 00:00:00 2001 From: Danny Coates Date: Fri, 16 Nov 2018 09:32:29 -0800 Subject: [PATCH] try out service worker cache --- app/serviceWorker.js | 21 ++++++++++++++++-- webpack.config.js | 51 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/app/serviceWorker.js b/app/serviceWorker.js index e110487d..91c885f1 100644 --- a/app/serviceWorker.js +++ b/app/serviceWorker.js @@ -1,3 +1,5 @@ +import assets from '../common/assets'; +import { version } from '../package.json'; import Keychain from './keychain'; import { downloadStream } from './api'; import { transformStream } from './streams'; @@ -8,11 +10,11 @@ let noSave = false; const map = new Map(); self.addEventListener('install', event => { - self.skipWaiting(); + event.waitUntil(precache()); }); self.addEventListener('activate', event => { - self.clients.claim(); + event.waitUntil(self.clients.claim()); }); async function decryptStream(id) { @@ -77,11 +79,26 @@ async function decryptStream(id) { } } +async function precache() { + const cache = await caches.open(version); + const x = assets.match(/.*\.(png|svg|jpg)$/); + await cache.addAll(x); + return self.skipWaiting(); +} + +async function cachedOrFetch(req) { + const cache = await caches.open(version); + const cached = await cache.match(req); + return cached || fetch(req); +} + self.onfetch = event => { const req = event.request; const match = /\/api\/download\/([A-Fa-f0-9]{4,})/.exec(req.url); if (match) { event.respondWith(decryptStream(match[1])); + } else { + event.respondWith(cachedOrFetch(req)); } }; diff --git a/webpack.config.js b/webpack.config.js index d1cd2011..a0414283 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -34,7 +34,56 @@ const serviceWorker = { path: path.resolve(__dirname, 'dist'), publicPath: '/' }, - devtool: 'source-map' + devtool: 'source-map', + module: { + rules: [ + { + include: [require.resolve('./assets/cryptofill')], + use: [ + { + loader: 'file-loader', + options: { + name: '[name].[hash:8].[ext]' + } + } + ] + }, + { + test: /\.(png|jpg)$/, + loader: 'file-loader', + options: { + name: '[name].[hash:8].[ext]' + } + }, + { + test: /\.svg$/, + use: [ + { + loader: 'file-loader', + options: { + name: '[name].[hash:8].[ext]' + } + }, + { + loader: 'svgo-loader', + options: { + plugins: [ + { removeViewBox: false }, // true causes stretched images + { convertStyleToAttrs: true }, // for CSP, no unsafe-eval + { removeTitle: true } // for smallness + ] + } + } + ] + }, + { + // loads all assets from assets/ for use by common/assets.js + test: require.resolve('./build/generate_asset_map.js'), + use: ['babel-loader', 'val-loader'] + } + ] + }, + plugins: [new webpack.IgnorePlugin(/\.\.\/dist/)] }; const web = {