Keeping it all N\*Sync with Background Sync

I am beyond lucky to know Carmen Bourlon. She’s a veteran JavaScript January contributor and has been such a generous teacher to the JavaScript community. Everyone loses connectionEveryone loses their internet connection at one time or another. Whether…


This content originally appeared on JavaScript January and was authored by Emily Freeman

I am beyond lucky to know Carmen Bourlon. She’s a veteran JavaScript January contributor and has been such a generous teacher to the JavaScript community.

Everyone loses connection

Everyone loses their internet connection at one time or another. Whether it's due to their Internet Service Provider, travel through an area without coverage, a hardware issue like a modem going out, or a Cloud Service Provider going down. Of course, none of these are predictable, and once any of these happen there isn't much any single person can do to resolve it. If an ISP goes down, everyone just has to wait until the issue is resolved. If a modem or router goes out, someone can order a new one, but they have to wait until it arrives.

Thank goodness we can add a service worker to our app to help when our users lose internet connection. With a service worker, we can save static assets directly to a user's machine to be served up when requests are made -- and even more we can cache API responses. But what happens when a user initiates a POST request right when their connection is lost?

Enter: Background Sync

Fortunately a service worker feature in process right now is background sync. And best of all, it's available in Google Chrome right now!

Note: Last year I wrote about using navigator.onLine and IndexedDB to create a background sync fallback for non-Chrome browsers.

This solution requires a working service worker, but once that's up and running, adding background sync is fairly simple.

Check out this blog post on how to write your first service worker!

So normally our service worker registration looks like this:

// index.js

if(navigator.serviceWorker) {
  navigator.serviceWorker.register('serviceworker.js');
}

We always want to wrap our service worker registration in an if-block in case our user is in an older browser, because older browsers do not support service workers. Let's adjust this registration to support background sync.

    // index.js
    
    if(navigator.serviceWorker) {
      navigator.serviceWorker.register('serviceworker.js')
      .then(registration => navigator.serviceWorker.ready)
      .then(function(registration) {
        if(registration.sync) {
          button.addEventListener('click', () => {
            return registration.sync.register('form-sync');
          });
        }
      });
    }

Let's look through this step-by-step. After the initial service worker registration, we wait for the navigator.serviceWorker.ready promise to resolve, which returns a ServiceWorkerRegistration object on the next line. Before we talked about how background sync isn't yet widely supported across modern browsers, so it's incredibly important to use feature detection with if(registration.sync).

On the next line we add a click even to our button which returns a sync event with a specific name.

Over in the service worker we add a small event listener to catch the events triggered in the view.

    // serviceworker.js
    
    self.addEventListener('sync', function(event) {
      if(event.tag == 'form-sync') {
        event.waitUntil(sendToServer());
      }
    });

There really isn't too much in the service worker event listener. It listens for any and all sync events, so within it we have an if-block to check for the specific sync event from the view. The important piece here is the event.waitUntil. We pass our POST function into event.waitUntil, and it's super important to take advantage of that method. If we didn't use event.waitUntil, our service worker could potentially "go back to sleep" before the POST function is complete. Using event.waitUntil keeps the service worker "awake" until the function is complete.

And there you have it! Background sync can provide one more way to help bridge the gap between online and offline.


This content originally appeared on JavaScript January and was authored by Emily Freeman


Print Share Comment Cite Upload Translate Updates
APA

Emily Freeman | Sciencx (2020-01-21T14:40:00+00:00) Keeping it all N\*Sync with Background Sync. Retrieved from https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/

MLA
" » Keeping it all N\*Sync with Background Sync." Emily Freeman | Sciencx - Tuesday January 21, 2020, https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/
HARVARD
Emily Freeman | Sciencx Tuesday January 21, 2020 » Keeping it all N\*Sync with Background Sync., viewed ,<https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/>
VANCOUVER
Emily Freeman | Sciencx - » Keeping it all N\*Sync with Background Sync. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/
CHICAGO
" » Keeping it all N\*Sync with Background Sync." Emily Freeman | Sciencx - Accessed . https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/
IEEE
" » Keeping it all N\*Sync with Background Sync." Emily Freeman | Sciencx [Online]. Available: https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/. [Accessed: ]
rf:citation
» Keeping it all N\*Sync with Background Sync | Emily Freeman | Sciencx | https://www.scien.cx/2020/01/21/keeping-it-all-nsync-with-background-sync/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.