try out service worker cache

This commit is contained in:
Danny Coates 2018-11-16 09:32:29 -08:00
parent 037c79730d
commit 660a1947cc
No known key found for this signature in database
GPG Key ID: 4C442633C62E00CB
2 changed files with 69 additions and 3 deletions

View File

@ -1,3 +1,5 @@
import assets from '../common/assets';
import { version } from '../package.json';
import Keychain from './keychain'; import Keychain from './keychain';
import { downloadStream } from './api'; import { downloadStream } from './api';
import { transformStream } from './streams'; import { transformStream } from './streams';
@ -8,11 +10,11 @@ let noSave = false;
const map = new Map(); const map = new Map();
self.addEventListener('install', event => { self.addEventListener('install', event => {
self.skipWaiting(); event.waitUntil(precache());
}); });
self.addEventListener('activate', event => { self.addEventListener('activate', event => {
self.clients.claim(); event.waitUntil(self.clients.claim());
}); });
async function decryptStream(id) { 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 => { self.onfetch = event => {
const req = event.request; const req = event.request;
const match = /\/api\/download\/([A-Fa-f0-9]{4,})/.exec(req.url); const match = /\/api\/download\/([A-Fa-f0-9]{4,})/.exec(req.url);
if (match) { if (match) {
event.respondWith(decryptStream(match[1])); event.respondWith(decryptStream(match[1]));
} else {
event.respondWith(cachedOrFetch(req));
} }
}; };

View File

@ -34,7 +34,56 @@ const serviceWorker = {
path: path.resolve(__dirname, 'dist'), path: path.resolve(__dirname, 'dist'),
publicPath: '/' 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 = { const web = {