Offline Support - Service Workers
Mobile web app
For my home automation project I needed a way to control devices and view their status, given that everything was running through a Laravel web server the obvious solution was a web app. I decided to use Vuejs for managing the front end as it's something I had been watching for a while, I just needed a reason to try it out.
The app came together fairly quickly and I ended up looking at the Nest mobile app for the initial inspiration as this was one of the motivations for building it. After getting it running and using it for a bit I quickly came across the one big limitation of web apps, offline support.
There are many ways to create an offline web app but some of the solutions such as the appcache weren't exactly easy to use. The modern solution that seems to solve most of these existing problems but still provide a lot of flexibility are service workers.
I tried various caching approaches but I ended up precaching the static resources when the application is installed, I had a list of defined assets that I was expecting and during the install process these are downloaded and stored. When an asset is fetched the url is checked and if it begins with api it is passed through unmodified, everything else gets matched against the cache and returned. By listing and caching everything upfront there should be nothing that ever misses the cache.
Once the application has been installed it can be opened up while offline and the ui loads up but no data is displayed, the application will attempt to make a request to the api but this fails gracefully and a styled error message is displayed.
I ran into a few problems getting it setup but the main one was updating the service worker; when you have the data cached you will occasionally need to update things especially as the software improves. When a cached page loads up it is supposed to try and download the service worker js file from the live server, it will then compare this against the one it has cached and if they differ it starts the process of updating the cached files. Unfortunately for me I couldn't never get it to reliably detect the file had changes, sometimes it took a few refreshes and sometimes I had to delve into the browser's internals and deregister the serviceworker. Given the success stories coming out about service worker I am fairly sure my experiences are unique and this behaviour was down to something I was doing wrong.
After getting this application running through a service worker I am very impressed with how easy it is to achieve quite a lot. Even if you cant manage an offline experience you can at least load an interface explaining this rather than falling back to the browsers offline message.