Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

Introduction to Service Worker

Introduction to Service Worker

2015/2/21に開催されたFrontrend Conferenceの「Introduction to Service Worker」のセッションの資料です。

Shogo Sensui

February 21, 2015
Tweet

More Decks by Shogo Sensui

Other Decks in Technology

Transcript

  1. var db; var objectStore; var req = window.indexedDB.open('dbname', 3); req.onsuccess

    = function(event) { db = event.target.result; }; req.onupgradeneeded = function(event) { db = event.target.result; objectStore = db.createObjectStore('name', { keyPath: 'key' }); };
  2. JOEFYFE%# ' ( ) * + # , - -

    - - - - - -  
  3. CACHE MANIFEST # Resource to cache CACHE: index.html stylesheet.css image.png

    script.js # Resource to bypass NETWORK: login.php /api/data # Fallback URLs FALLBACK: / /offline.html
  4. if (navigator.onLine) { $.ajax({ url: '/api/data', method: 'get' }).done(function (data)

    { render(data); }); } else { var cacheData = localStorage.getItem('key'); render(JSON.parse(cacheData)); }
  5. var sw = navigator.serviceWorker; sw.register('sw.js').then(function (res) { console.log('sw.js is installed!');

    }, function (error) { console.log('sw.js is not installed...'); }); JO#SPXTFS
  6. var sw = navigator.serviceWorker; sw.ready.then(function(reg) { reg.syncManager.register({ id: "periodicSync", minDelay:

    60 * 60 * 1000, minPeriod: 12 * 60 * 60 * 1000, allowOnBattery: true idleRequired: false }).then(function() { // Success }); }); JO#SPXTFS
  7. var sw = navigator.serviceWorker; sw.ready.then(function(reg) { reg.pushManager.subscribe().then( function(subscription) { //

    Success console.log(subscription.subscriptionId); console.log(subscription.endpoint); } }); }); JO#SPXTFS
  8. e.respondWith( caches.open(CACHE_KEY).then(function (cache) { return cache.match(e.request) .then(function (response) { if

    (response) { return response; } else { return fetch(e.request.clone()) .then(function (res) { cache.put(e.request, res.clone()); return res; }); } }); }) ); JO4FSWJDF8PSLFS