From 1d949a1ab2ed99b1e85e7b89ce7006eb048111c7 Mon Sep 17 00:00:00 2001 From: Lim Chee Aun Date: Tue, 17 Sep 2024 19:04:10 +0800 Subject: [PATCH] Try this solution to clean up excess SW cache --- src/main.jsx | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main.jsx b/src/main.jsx index a7084818..75435bca 100644 --- a/src/main.jsx +++ b/src/main.jsx @@ -48,6 +48,30 @@ setTimeout(() => { } catch (e) {} }, 5000); +// Service worker cache cleanup +if ('serviceWorker' in navigator && typeof caches !== 'undefined') { + const MAX_SW_CACHE_SIZE = 300; + let swInterval = setInterval(() => { + if (window.__IDLE__) { + clearInterval(swInterval); + (async () => { + const keys = await caches.keys(); + for (const key of keys) { + const cache = await caches.open(key); + const _keys = await cache.keys(); + if (_keys.length > MAX_SW_CACHE_SIZE) { + console.warn('Cleaning cache', key, _keys.length); + const deleteKeys = _keys.slice(MAX_SW_CACHE_SIZE); + for (const deleteKey of deleteKeys) { + await cache.delete(deleteKey); + } + } + } + })(); + } + }, 15_000); +} + window.__CLOAK__ = () => { document.body.classList.toggle('cloak'); };