Keep working Offline with Javascript
Junior Oliveira
Posted on April 21, 2019
Note: It was originally wrote in Portuguese and translated by Google
Let’s use as an example a system of messages exchange, where each message that you send is stored in a database for later to be displayed to someone. It could be a chat.
Now let’s imagine that you are using this system on your mobile and your connection is suffering oscillations due to bad connection with the carrier… In this case, some of your messages might not be delivered.
Recently I have known the Offline-js lib that monitors the status of your connection, issues alerts in case of drops, alerts when it returns, also monitors ajax requests and tries to resend them as soon as the connection returns.
It also promises to do everything in an “automagic” way, you just need to import the library and that’s it. At first I thought it was beautiful, it was all I needed to solve the issues in my application.
But it is not that perfect. As soon as I started to test with this lib, bugs started to appear … I went to search the issues and had more people with similar problems, but nobody answers the issues! There are also a number of pull requests with fixes and no one accepts.
So I decided to use it as a dependency for some features and make my own implementation: https://github.com/arojunior/handle-failed-requests-js
- Promises support (axios)
- Uses localStorage to save requests
- Saves ALL the failed requests, not just the last one
- Requests keep saved even if user try to refresh the page when offline
- Sends all requests as soon as the connection is restored
- No configuration needed
Use case:
Using this method, whenever a request fails, it will be stored in localStorage and once the connection is restored, it will be sent again.
It is not a silver bullet, it is not about cache as well. You probably are thinking “why don’t you use Service Workers?”. Because SW is not compatible with all browsers, but localStorage is. That’s why.
It is an extremely simple implementation to use and understand. If you have any suggestion, feel free to comment or send pull request.
Posted on April 21, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.