DEV Community

Junior Oliveira
Junior Oliveira

Posted on • Originally published at on

Keep working Offline with Javascript

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:

  • 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.

Top comments (3)

akshatbhargava123 profile image

There's navigator.isOnline then why do we need it?

arojunior profile image
Junior Oliveira

Hi! Thank you for your feedback. Actually, is just a Boolean and the correct property is "onLine" from navigator.

We need it because as I said before, it's just a Boolean to tell you when is online/offline... But how do you keep the failed request to send again when it came from offline to online?

The real meaning of this library is about do not lose requests.

akshatbhargava123 profile image

Ohhh okay, I get the point now. Thank you so much!