Service Worker: Another attempt to fix freezing UI on iOS
This commit is contained in:
parent
1abb31e3ee
commit
0e4c3cb123
@ -1,12 +1,22 @@
|
|||||||
import { ASSET_CACHE_NAME } from '../config';
|
import { ASSET_CACHE_NAME } from '../config';
|
||||||
|
import { pause } from '../util/schedulers';
|
||||||
|
|
||||||
declare const self: ServiceWorkerGlobalScope;
|
declare const self: ServiceWorkerGlobalScope;
|
||||||
|
|
||||||
export async function respondWithCache(e: FetchEvent) {
|
// An attempt to fix freezing UI on iOS
|
||||||
const cache = await self.caches.open(ASSET_CACHE_NAME);
|
const CACHE_TIMEOUT = 3000;
|
||||||
const cached = await cache.match(e.request);
|
|
||||||
|
|
||||||
if (cached) {
|
export async function respondWithCache(e: FetchEvent) {
|
||||||
|
const cacheResult = await withTimeout(async () => {
|
||||||
|
const cache = await self.caches.open(ASSET_CACHE_NAME);
|
||||||
|
const cached = await cache.match(e.request);
|
||||||
|
|
||||||
|
return { cache, cached };
|
||||||
|
}, CACHE_TIMEOUT);
|
||||||
|
|
||||||
|
const { cache, cached } = cacheResult || {};
|
||||||
|
|
||||||
|
if (cache && cached) {
|
||||||
if (cached.ok) {
|
if (cached.ok) {
|
||||||
return cached;
|
return cached;
|
||||||
} else {
|
} else {
|
||||||
@ -16,13 +26,26 @@ export async function respondWithCache(e: FetchEvent) {
|
|||||||
|
|
||||||
const remote = await fetch(e.request);
|
const remote = await fetch(e.request);
|
||||||
|
|
||||||
if (remote.ok) {
|
if (remote.ok && cache) {
|
||||||
cache.put(e.request, remote.clone());
|
cache.put(e.request, remote.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
return remote;
|
return remote;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function withTimeout<T>(cb: () => Promise<T>, timeout: number) {
|
||||||
|
try {
|
||||||
|
return await Promise.race([
|
||||||
|
pause(timeout).then(() => Promise.reject(new Error('TIMEOUT'))),
|
||||||
|
cb(),
|
||||||
|
]);
|
||||||
|
} catch (err) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error(err);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function clearAssetCache() {
|
export function clearAssetCache() {
|
||||||
return self.caches.delete(ASSET_CACHE_NAME);
|
return self.caches.delete(ASSET_CACHE_NAME);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user