Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Service Worker basics

Service Worker basics

Avatar for yujing.wang

yujing.wang

March 03, 2017

More Decks by yujing.wang

Other Decks in Technology

Transcript

  1. AppCache <html lang="en" manifest="offline.appcache"> CACHE MANIFEST #v1 CACHE assets/8/script/mainmin.js assets/8/style/all-min.css

    assets/8/style/fonts/oswald.ttf assets/8/style/imgs/sprites1.png assets/8/tutorial-sprite.png assets/8/favicon.ico NETWORK: * FALLBACK http://www.spritecow.com/
  2. AppCache <script>
 window.applicationCache.addEventListener("updateready", function(){
 window.location.reload()
 });
 </script> • HTML? cached!

    Update rely on the .appcache file.ҁjava, php) • Cache time(max-age, expires) • Use cached file forever, urmmmm • Reload needed. • One cache error, all fail • …
  3. Service worker • script(no CDN) • run in Background •

    own context • https(except:localhost) • a server? • request & response - proxy • offline experience - storage • run task in background - worker • push,sync,geofencing • balabala…
  4. Service worker Registration if (navigator.serviceWorker) {
 console.log('ServiceWorker supported!');
 navigator.serviceWorker.register('sw.js', {scope:

    './'})
 .then(function (reg) {
 console.log('ServiceWorker works in the scope ', 'SCOPE:' + reg.scope);
 })
 .catch(function (err) {
 console.log('ServiceWorker failed ', err);
 });
 } • scope • two service workers Note
  5. Service worker Life Cycle Installing Installed Activating Activated Redundant •

    event.waitUntil() • Redundant any time(e.g. new SW) Note
  6. Service worker Installation var CACHE_NAME = 'cache_1';
 
 var urlsToCache

    = [
 './index1.html',
 './script/test.js',
 './style/test.css',
 './icon.png'
 ];
 
 self.addEventListener('install', function (event) {
 event.waitUntil(
 caches.open(CACHE_NAME)
 .then(function (cache) {
 console.log('Opend indexdb ', cache);
 return cache.addAll(urlsToCache);
 })
 );
 }); • waitUntil promise Note
  7. Service worker Activation self.addEventListener('activate', function (event) {
 var whiteList =

    ['cache_1'];
 event.waitUntil(
 caches.keys().then(function (cacheNames) {
 return Promise.all(
 cacheNames.map(function (cacheName) {
 console.log(cacheName, whiteList.indexOf(cacheName) == -1);
 if (whiteList.indexOf(cacheName) == -1) {
 caches.delete(cacheName);
 }
 })
 )
 })
 );
 }); • waitUntil promise Note
  8. Service worker Request & Response self.addEventListener('fetch', function (event) {
 event.respondWith(


    caches.match(event.request)
 .then(function (response) {
 if (response) {
 return response;
 }
 
 return fetch(event.request);
 var requestClonse = event.request.clone();
 return fetch(requestClone).then(function (response) {
 if (!response || response.status != 200) {
 return response;
 }
 
 var responseClone = response.clone();
 caches.open(CACHE_NAME).then(function (cache) {
 cache.put(event.request, responseClone);
 });
 });
 })
 )
 });
  9. Service worker Update • Check byte by byte • new

    version will take control next time • self.skipWaiting() • self.clients.claim() Note Unregistering navigator.serviceWorker.getRegistration().then(function(reg) {
 reg.unregister();
 });
  10. Service worker WebApp Manifest <link rel="manifest" href="manifest.json"> “The web app

    manifest provides information about an application (such as name, author, icon, and description) in a text file. The purpose of the manifest is to install web applications to the homescreen of a device, providing users with quicker access and a richer experience.” {
 "name": "Manifest Demo",
 "display": "standalone",
 "background_color": "#ccc",
 "start_url": ".",
 "icons": [{
 "src": "icon.png",
 "sizes": "144x144",
 "type": "image/png"
 }]
 } • use with SW Note
  11. Service worker Further reading • https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Custom_responses_to_requests • http://www.cnblogs.com/yexiaochai/p/4271834.html • http://alistapart.com/article/application-cache-is-a-douchebag

    • http://gold.xitu.io/entry/56c57e25816dfa00598296c0 • https://developer.mozilla.org/en/docs/Web/API/Service_Worker_API • https://developer.mozilla.org/en-US/docs/Web/Manifest • https://github.com/GoogleChrome/sw-toolbox