As I earlier have written about what progressive web apps are, I am now writing about how to make them offline usable. Of course, this is an advantage of the progressive web apps.
First of all, you need to know that not all web application can be offline usable. When you still need a connection to your server, because of updates, then it does not make sense to create an offline app. But you can still enable a “caching” function which is sometimes useful. For example, you are a news agency publishing news articles. Of course, now the client needs a connection to the server, but once he had that, he should be able to also view the articles even if he turns offline.
How to get started
Make sure, that you have read my recent article about progressive web apps here. After you have created the service worker you should now be able to be ready for the offline implementation.
In the following script, you will find an array with defined file names. These are all files, which should be stored in the cache for later offline usage.
In the install script, this caching function does take place. In the function below “fetch”, you see that it will first check if it is a GET Request (otherwise the caching functionality does not work) and after that tries to fetch the content from the internet. In case if it cannot connect to the URL, it will throw an error and calls the catch function, which now tries to return the cached file from the previous installation.
Actually, this is how to make your web app offline useable if you do not require any connection to the server afterward. But if you still need some requests, then I can really recommend you to take a look at the following attribute:
navigator.onLine
This attribute indicates whenever you are offline or online. This could be useful to call different functions in your script. For example, if you want to load new articles then check first if the user is connected to the internet, so that it can access the server or when he is not afterward, that it will load articles from the previous load.
Data storing online and offline
Of course, there are also already some implementations for storing data even when the user is not online. For that, you should take a look for the IndexedDB. This database is a NoSQL database and is based on documents like FireStore from Firebase by Google or MongoDB.
There are many tutorials about how to use this database. Here are some examples:
I already used as well IndexedDB in my weather app, to store the locations, which the user has been added during he was offline and sync them with the API to match the cities. If you want to take a look, you can check it here.
Featured photo from Sten Ritterfeld on Unsplash
Leave a Reply