service worker, attempt 1

This commit is contained in:
remi 2022-06-12 00:14:06 +02:00
parent 9fb89f31d5
commit 05623222c8
5 changed files with 174 additions and 30 deletions

View File

@ -40,6 +40,7 @@
<a id="showAllWords">show all words</a> <a id="randomWord">random word</a> <a href="#">resources</a> <a id="showAllWords">show all words</a> <a id="randomWord">random word</a> <a href="#">resources</a>
</div> </div>
<noscript>turn on js doofus</noscript> <noscript>turn on js doofus</noscript>
<span id="update">update available! close all open hisho tabs and reopen hisho to update.</span>
</header> </header>
<main> <main>

View File

@ -160,6 +160,10 @@ header.fullscreen #search {
max-width: 500px; max-width: 500px;
} }
header #update {
display: none;
}
.header-animation { .header-animation {
animation: clearly-cheating 1s ease-in-out; animation: clearly-cheating 1s ease-in-out;
} }

50
main.js
View File

@ -476,6 +476,53 @@ function goHome(state = true) {
if (state == true) history.pushState(null, "", url); if (state == true) history.pushState(null, "", url);
} }
async function registerSW() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
header.querySelector("#update").style.display = "block";
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
}).catch(error => {
console.error('Error during service worker registration:', error);
});
}
}
function removeSW() {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for(let registration of registrations) {
registration.unregister()
}}); //dev use only!! or whatever... i just copypasted this from SO
}
window.onload = () => { window.onload = () => {
header = document.querySelector("header"); header = document.querySelector("header");
main = document.querySelector("main"); main = document.querySelector("main");
@ -513,7 +560,8 @@ window.onload = () => {
doSearch(false); doSearch(false);
} }
}); });
//also check if ?s is there . for hecks sake (todo) registerSW();
//also check if ?s is there . for hecks sake (todo) (TODO!!!!!!)
} }
const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {}) const sortObject = obj => Object.keys(obj).sort().reduce((res, key) => (res[key] = obj[key], res), {})

91
sw.js Normal file
View File

@ -0,0 +1,91 @@
const currentVersion = 'v1';
const addResourcesToCache = async (resources) => {
const cache = await caches.open(currentVersion);
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
const cache = await caches.open(currentVersion);
await cache.put(request, response);
};
const cacheFirst = async ({ request, preloadResponsePromise }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to use the preloaded response, if it's there
const preloadResponse = await preloadResponsePromise;
if (preloadResponse) {
console.info('using preload response', preloadResponse);
putInCache(request, preloadResponse.clone());
return preloadResponse;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request);
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
return new Response('Network error happened', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
});
}
};
const deleteCache = async key => {
await caches.delete(key)
}
const deleteOldCaches = async () => {
const cacheKeepList = [currentVersion];
const keyList = await caches.keys()
const cachesToDelete = keyList.filter(key => !cacheKeepList.includes(key))
await Promise.all(cachesToDelete.map(deleteCache));
}
self.addEventListener('activate', (event) => {
event.waitUntil(deleteOldCaches());
});
const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) {
// Enable navigation preloads!
await self.registration.navigationPreload.enable();
}
};
self.addEventListener('activate', (event) => {
event.waitUntil(enableNavigationPreload());
});
self.addEventListener('install', (event) => {
event.waitUntil(
addResourcesToCache([
'./heonian-resources/wordlist.json',
'./heonian-ime/ime.js',
'./font.otf',
'./index.html',
'./main.css',
'./main.js',
'./manifest.json'
])
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
cacheFirst({
request: event.request,
preloadResponsePromise: event.preloadResponse
})
);
});

BIN
temp.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB