Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Always on! Or not?

104 views

Published on

My Slides about creating web sites which could also be useable even if you are not online! From Web Storages to Service Workers.

Presented at Mobiletech Conference in Munich March 2017

Published in: Internet
  • Be the first to comment

  • Be the first to like this

Always on! Or not?

  1. 1. Always ON! …or not? Carsten Sandtner (@casarock) mediaman GmbH
  2. 2. about:me Carsten Sandtner @casarock Technical Director mediaman GmbH
  3. 3. The Beginning NilsPeters-https://flic.kr/p/9k2Wdp
  4. 4. Browser Cache
  5. 5. Cookies BrettJordan-https://flic.kr/p/7ZRSzA
  6. 6. Ancient Times ThomasConté-https://flic.kr/p/9dzzpc
  7. 7. Application Cache
  8. 8. „HTML5 provides an application caching mechanism that lets web-based applications run offline. Developers can use the Application Cache (AppCache) interface to specify resources that the browser should cache and make available to offline users.“ -MDN https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache
  9. 9. The TRUTH
  10. 10. • FILES ALWAYS COME FROM THE APPLICATIONCACHE, EVEN IF YOU’RE ONLINE • THE APPLICATIONCACHE ONLY UPDATES IF THE CONTENT OF THE MANIFEST ITSELF HAS CHANGED • THE APPLICATIONCACHE IS AN ADDITIONAL CACHE, NOT AT ALTERNATIVE ONE • NEVER EVER EVER FAR-FUTURE CACHE THE MANIFEST • NON-CACHED RESOURCES WILL NOT LOAD ON A CACHED PAGE • WE DON’T KNOW HOW WE GOT TO THE FALLBACK PAGE • …
  11. 11. – Jake Archibald http://alistapart.com/article/application-cache-is-a-douchebag „Application Cache is a Douchebag“
  12. 12. 2016 W3C decides to remove application cache from standard
  13. 13. AlexanderBoden-https://flic.kr/p/pMrQ1N Things are getting better
  14. 14. Web Storages
  15. 15. Web Storages • key/value store • localStorage • sessionStorage
  16. 16. localStorage localStorage.myCar = 'Volkswagen Beetle'; localStorage['myCar'] = 'Volkswagen Beetle'; localStorage.setItem('myCar', 'Volkswagen Beetle'); let myCar = localStorage.getItem('myCar'); window.addEventListener('storage', function(e) { ... } localStorage.removeItem('myCar'); localStorage.clear() let complexType = {type: 'Beetle', manufacturer: 'Volkswagen'} localStorage.setItem('myCar', JSON.stringify(complexType));
  17. 17. sessionStorage sessionStorage.myCar = 'Volkswagen Beetle'; sessionStorage['myCar'] = 'Volkswagen Beetle'; sessionStorage.setItem('myCar', 'Volkswagen Beetle'); let myCar = sessionStorage.getItem('myCar'); window.addEventListener('storage', function(e) { ... } sessionStorage.removeItem('myCar'); sessionStorage.clear() let complexType = {type: 'Beetle', manufacturer: 'Volkswagen'} sessionStorage.setItem('myCar', JSON.stringify(complexType));
  18. 18. WebStorages • easy to use! • good browser support! • But: • http/https define different stores! • asynchronous • Quota?
  19. 19. IndexedDB
  20. 20. –Wikipedia https://en.wikipedia.org/wiki/Indexed_Database_API „The Indexed Database API, or IndexedDB (formerly WebSimpleDB), is a W3C recommended web browser standard interface for a transactional local database of JSON objects collections with indices.“
  21. 21. IndexedDB: Open/Create var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; var open = indexedDB.open("MyDatabase", 1); // Create the schema open.onupgradeneeded = function() { var db = open.result; var store = db.createObjectStore("FancyNamedStore", {keyPath: "id"}); var index = store.createIndex("NameIndex", ["name.last", "name.first"]); }; open.onsuccess = function() {}; open.onfailure = function() {};
  22. 22. IndexedDB: Write/Read open.onsuccess = function() { var db = open.result; var tx = db.transaction("FancyNamedStore", "readwrite"); var store = tx.objectStore("FancyNamedStore"); var index = store.index("NameIndex"); store.put({id: 12345, name: {first: "John", last: "Bar"}, age: 42}); store.put({id: 67890, name: {first: "Bob", last: "Foo"}, age: 35}); var getJohn = store.get(12345); var getBob = index.get(["Foo", "Bob"]); getJohn.onsuccess = function() { console.log(getJohn.result.name.first); // => "John" }; getBob.onsuccess = function() { console.log(getBob.result.name.first); // => "Bob" }; tx.oncomplete = function() { db.close(); }; }
  23. 23. localForage* FTW! * or any other library… like Store.js 
 (https://github.com/marcuswestin/store.js/)
  24. 24. „localForage is a JavaScript library that improves the offline experience of your web app by using an asynchronous data store with a simple, localStorage- like API. It allows developers to store many types of data instead of just strings.“ –https://localforage.github.io
  25. 25. „localForage includes a localStorage-backed fallback store for browsers with no IndexedDB or WebSQL support. Asynchronous storage is available in the current versions of all major browsers: Chrome, Firefox, IE, and Safari (including Safari Mobile).“ –https://localforage.github.io
  26. 26. „localForage offers a callback API as well as support for the ES6 Promises API, so you can use whichever you prefer.“ –https://localforage.github.io
  27. 27. LocalForage localforage.config({ driver : localforage.WEBSQL, // localforage.INDEXEDDB // localforage.WEBSQL // localforage.LOCALSTORAGE name : 'carFinder', version : 1.0, size : 4980736, // Size of database, in bytes. WebSQL-only for now. storeName : 'mycars', // Should be alphanumeric, with underscores. description : 'Store all infos about my cars' }); localforage.setItem('car', 'beetle').then(function () { return localforage.getItem('car'); }).then(function (value) { // Success, we've got a value }).catch(function (err) { // something went wrong });
  28. 28. Modern Times Image©byAppleComputerInc.
  29. 29. Service Workers
  30. 30. — https://github.com/w3c/ServiceWorker „Service workers are a new browser feature that provide event-driven scripts that run independently of web pages. Unlike other workers, service workers can be shut down at the end of events, note the lack of retained references from documents, and they have access to domain-wide events such as network fetches.“
  31. 31. — https://github.com/w3c/ServiceWorker „Service workers also have scriptable caches. Along with the ability to respond to network requests from certain web pages via script, this provides a way for applications to “go offline”.“
  32. 32. Introduction
  33. 33. ☁🖥 Internet 1 2
  34. 34. ☁🖥 Internet 📜Service Worker 1 2 3
  35. 35. ☁ 🖥 Internet 📜Service Worker 📁Cache 1 2 3 3
  36. 36. ☁ 🖥 Internet 📜Service Worker 📁Cache 5 3 2 4 1
  37. 37. ☁ 🖥 Internet 📜Service Worker 📁Cache ❌ 1 2 3 4
  38. 38. Code
  39. 39. Register Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'}) .then(function(reg) { // registration worked console.log('Registration succeeded. Scope is ' + reg.scope); }).catch(function(error) { // registration failed console.log('Registration failed with ' + error); }); }
  40. 40. Service Worker Overview self.addEventListener('install', function(event) { console.log("installed"); }); self.addEventListener('activate', function(event) { console.log("activated"); }); self.addEventListener('fetch', function(event) { console.log("fetch"); event.respondWith(new Response("My response!!")); });
  41. 41. Install self.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/images/myImage.png', '/index.html' ]); }) ); });
  42. 42. Fetch this.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); });
  43. 43. Fetch & Update Cache this.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(resp) { return resp || fetch(event.request).then(function(response) { caches.open('v1').then(function(cache) { cache.put(event.request, response.clone()); }); return response; }); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); }) ); });
  44. 44. Clean Up Cache this.addEventListener('activate', function(event) { var cacheWhitelist = ['v2']; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); });
  45. 45. Update Cache var CACHE_NAME = 'static-v9'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME_STATIC).then(function(cache) { return cache.addAll(['...']); }) ) }); self.addEventListener('activate', function(event) { var cacheWhitelist = [CACHE_NAME_STATIC]; event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (cacheWhitelist.indexOf(key) === -1) { return caches.delete(key); } })); }) ); });
  46. 46. We have the tools!
  47. 47. https://jakearchibald.github.io/isserviceworkerready/
  48. 48. GonzaloBaeza-https://flic.kr/p/dCPzuE Now & The Future
  49. 49. Progressive Web Apps
  50. 50. –Ada Rose Edwards https://www.smashingmagazine.com/2016/09/the-building-blocks-of-progressive-web-apps/ „An ideal web app is a web page that has the best aspects of both the web and native apps. It should be fast and quick to interact with, fit the device’s viewport, remain usable offline and be able to have an icon on the home screen.“
  51. 51. OMG! PWA? WTF? • Progressive • Responsive • Connectivity independent • App-like • Safe • Discoverable • Installable • Linkable
  52. 52. PWA Architecture „Thorsten“-https://flic.kr/p/y3ib6k
  53. 53. App Shell
  54. 54. Service Workers www.audio-luci-store.it-https://flic.kr/p/hQannE
  55. 55. Installability
  56. 56. Push Notification • Allow SW to wake up • Works in Background, only SW is woken up • Needs permission from user!
  57. 57. –W3C https://w3c.github.io/push-api/ „The Push API enables sending of a push message to a webapp via a push service.“
  58. 58. And Webpages?
  59. 59. –Slightly modified by me… „An ideal web page is a web page that has the best aspects of both the web and native apps. It should be fast and quick to interact with, fit the device’s viewport and remain usable offline and be able to have an icon on the home screen.“
  60. 60. Cache Data from APIs • localStorage • sessionStorage • IndexedDB
  61. 61. Are you online? var online = navigator.onLine; if (!online) { // Fallback -> Get Data from Storage! } else { // Use network.... }
  62. 62. That’s easy!
  63. 63. Wait? • Slow network? (Edge, GPRS etc.) • mobile networks are not reliable… • „Lie“-Fi
  64. 64. Use Service Workers • Provide offline fallback • Cache static files • Controll the network ;)
  65. 65. Demo https://github.com/casarock/service-worker-demo
  66. 66. GPRS
  67. 67. GPRS + SW
  68. 68. Considerations • Don't abuse offline caches. • How to deal with sensitive information? • Are my assets permanently stored? • Think about your use case!
  69. 69. Always on is a lie. Carsten Sandtner @casarock sandtner@mediaman.de https://github.com/casarock ¯_(ツ)_/¯

×