Start codelab

Codelab Flow

What you will learn

L Last updated on 01/12/18 W Background Sync

In this codelab you will learn how to add background sync to your Progressive Web App. Service Workers solve the page loading part by letting you serve content from a cache. But what about when the page needs to send something to the server 😲 ?

How to configure

To your javascript source folder, create an empty sync.js file and copy and paste the code snippet below to it. Remember to add it to your pages at the botton of your project's pages as shown at the botton of this githhub doc 😊

Background Sync is activated once your page is loaded by default. Though you could re-configure this to anything. Maybe listen to events like on click with javascript.
Background Sync is activated once your page is loaded by default. Though you could re-configure this to anything. Maybe listen to events like on click with javascript.
   
// https://pwafire.org

(function (window) {
    'use strict';
    // Add background sync on page load
    document.addEventListener("DOMContentLoaded", function() {
      window.registerBGSync();
    });
    // Exposing `registerSync()` globally for only development purpose
    window.registerBGSync = function() {
      //If `serviceWorker` is registered and ready
      navigator.serviceWorker.ready
        .then(function (registration) {
          //Registering `background sync` event
          return registration.sync.register('Comments') 
           // `Comments` is sync tag name ; could be anything 😉
            .then(function (rs) {
              console.info('Background sync registered!');
            }, function () {
              console.error('Background sync registered failed.');
            });
  
        });
    }
  })(window);
    

What's next?

We shall be publishing another codelab on how to add push notifications to your progressive web app. Taking these codelabs allows you to build small but exciting web experiences for your target users.

Support

Donate a Star and Contribute in any way. Be sure to follow us on Twitter. If you use web-share kindly let us know via info@pwafire.org or JUST simply Tweet us

License

Copyright PWA Fire, 2018. Licensed under an MIT License.

FORK ON GITHUB