I have just created my first PWA for a reference app using offline functions. After referencing online tutorials, You Tube and Stack Overflow I was able to get a service worker up and running and it seemed to work really well.
The PWA has a list of PDF reference documents that are cached at install. I am then using a cache first approach as there are around 125 documents that rarely change. Both iOS and Android devices had seemed to be working great with the offline functionality. When you put the mobile device in airplane mode, all the referenced documented loaded instantly.
The issue is this only lasts a few days, somewhere around 5 days. Then when clicking a link on the main PWA page, instead of loading the PDF an error is displayed.
Safari can’t open the page. The error was: “FetchEvent.respondWith
received an error: TypeError: Load failed”.
Chrome in Windows does similar, console shows
Uncaught (in promise) TypeError: Failed to fetch
This points me to my cacheFirst function. Which I will wrap in a try/catch and then output the error or a PWA custom 404 eventually.
function cacheFirst(ev) {
//return from cache or fetch if not in cache
return caches.match(ev.request).then((cacheResponse) => {
//return cacheResponse if not null
return cacheResponse || fetch(ev.request);
});
}
I am questioning if I am really getting the offline files from the service worker or is really the browser cache supplying the page? I feel like it is truly the SW as when I initially install the app and go offline, I can open and of the 125 PDFs I want… even if I have never opened that link before for the browser to cache. Why then is my PWA cache being destroyed after a few days? My understanding these were basically persistent, unless the user clears a cache, runs out of space, etc.
From Chrome Developer Tools > Application > Cache Storage I go from seeing a list of ALL my files, including PDFs, at install, to eventually 5 core web page files… likely the ones that were browsed more recently. If I change my clock on my computer from today to a month in the future I can watch the PWA caching process break and then upon returning the date to present the PWA cache works again.
I feel REALLY close, but I missed out on something to make the PWA cache persists. I have read that navigator.storage.persist can help correct this for IndexedDB. Does it have the same effect on the cache?