Background Sync - Steroid for Web Apps

Dani Vijay
Beginner's Guide to Mobile Web Development
3 min readMay 11, 2018

While doing Google Udacity Challenge Scholarship for Mobile Web Specialist track, I happened to know about Background Sync. A technology that can be used do things even after web app is closed! Voila!! The gap between native apps and web apps is getting thin day by day. And, this is a huge step forward. But how can we use it in our favour?

In the application level, the process can be concluded in this way: queue events within the browser, that will fire in your Service Worker when the browser has network connectivity. Thanks to the service worker, it works even if the app is not open in the web browser.

Let’s do a sync

Start by registering a service worker. Then we can set up the sync.

// Register your service worker:
navigator.serviceWorker.register('/sw.js');

// Then later, request a one-off sync:
navigator.serviceWorker.ready.then(function(swRegistration) {
return swRegistration.sync.register('myFirstSync');
});

Now you can listen to the sync on /sw.js

self.addEventListener('sync', function(event) {
if (event.tag == 'myFirstSync') {
event.waitUntil(doSomeStuff());
}
});

The doSomeStuff() should be a promise. If it fails, the event will be rescheduled. Retry syncs also wait for connectivity, and employ an exponential back-off.

The tag name of the sync ( myFirstSync in this case) should be unique. If you use same, it just combines with the existing. So different tag names should be used to create different sync events.

What if browser not supported?

Progressive enhancements are here to rescue.

if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready.then(function(reg) {
return reg.sync.register('tag-name');
}).catch(function() {
// system was unable to register for a sync,
// this could be an OS-level restriction
doItNormally();
});
} else {
// serviceworker/sync not supported
doItNormally();
}

If service workers or background sync aren’t available, we can tell browser just do it in the normal way. In this case, it’ll trigger doItNormally().

Whats next?

No permissions are needed for the background sync feature. It can be used together with other PWA features such as push notifications, which may require permissions.

Applications for background sync are endless. It just gives developer the power trigger some event even the app is closed. This gives capabilities similar to native apps. Only limit is your imagination!

Browser support is somewhat limited in the time of writing. You can check the latest state here: https://caniuse.com/#search=Background%20Sync

Read more on Google Developers : https://developers.google.com/web/updates/2015/12/background-sync

Feel free to connect and chit chat with me on Twitter and LinkedIn, or code together on GitHub. Claps will fuel me to write more. Have a nice day!!

--

--