service worker

Offline strategy

  • Appcache: using manifest
    • single page limit
    • refresh
  • localstorage
    • size limit
  • indexDB
  • service worker

what is the service worker

characteristic

life cycle

how to use

register

  • is browser support serviceWorker
  • the cache only avaliable in the path of sw.js
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ',    registration.scope);
  }).catch(function(err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}

install

  • open a cache
  • add resources to cache
  • forces the waiting service worker to become the active service worker
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  '/',
  '/styles/main.css',
  '/script/main.js'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      }).then(self.skipWaiting())
  );
});

cache API

  • The Cache interface provides a storage mechanism for Request / Response object pairs that are cached
  • cache API: match addAll map ...
  • cache polyfill

fetch

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

active

self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

examples

例子

indepth: push API

例子

  • Check if browser supports service worker & push messaging
  • Notification.requestPermission()
  • register push & click event handle function
  • when ready: navigator.serviceWorker.ready
  • Get Server API key and Sender ID from GCM
  • generate subscripionId: serviceWorkerRegistration.pushManager.subscribe
  • wait to get push message
self.addEventListener('push', function(event) {
  //do push thing
});

self.addEventListener('notificationclick', function(event) {
   // handle notification popup  
});

indepth: background-sync

https://jakearchibald-gcm.appspot.com/

代码

self.addEventListener('sync', event => {
  if (event.tag == 'postOutbox') {
    event.waitUntil(postOutbox());
  }
});

more

  • only used in https protoca
  • support: chrome 49+ android 5.x.x Opera Firefox IE Edge