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?
Carsten Sandtner (@casarock)
mediaman// Gesellschaft für Kommunikation mbH
about:me
Carsten Sandtner
@casarock
Head of Software Development
//mediaman GmbH
The Beginning
NilsPeters-https://flic.kr/p/9k2Wdp
Browser Cache
Cookies
BrettJordan-https://flic.kr/p/7ZRSzA
Ancient Times
ThomasConté-https://flic.kr/p/9dzzpc
Application
Cache
„HTML5 provides an application caching mechanism
that lets web-based applications run offline.
Developers can use the Applic...
AppCache: Definition
<!DOCTYPE html>
<html lang="en" manifest="cache.manifest">
AppCache: Manifest
CACHE MANIFEST
# v2 2016-09-30
index.html
cache.html
style.css
app.js
hero.png
# Use from network if av...
AppCache: Javascript
window.applicationCache.onchecking = function(e) {}
window.applicationCache.onnoupdate = function(e) ...
The
TRUTH
• FILES ALWAYS COME FROM THE APPLICATIONCACHE, EVEN IF YOU’RE
ONLINE
• THE APPLICATIONCACHE ONLY UPDATES IF THE CONTENT OF...
– Jake Archibald
http://alistapart.com/article/application-cache-is-a-douchebag
„Application Cache is a Douchebag“
2016
W3C decides to remove application cache
from standard
AlexanderBoden-https://flic.kr/p/pMrQ1N
Things are getting better
Web
Storages
Web Storages
• key/value store
• localStorage
• sessionStorage
localStorage
localStorage.myCar = 'Volkswagen Beetle';
localStorage['myCar'] = 'Volkswagen Beetle';
localStorage.setItem('...
sessionStorage
sessionStorage.myCar = 'Volkswagen Beetle';
sessionStorage['myCar'] = 'Volkswagen Beetle';
sessionStorage.s...
WebStorages
• easy to use!
• good browser support!
• But:
• http/https define different stores!
• asynchronous
• Quota?
IndexedDB
–Wikipedia
https://en.wikipedia.org/wiki/Indexed_Database_API
„The Indexed Database API, or IndexedDB (formerly
WebSimpleD...
IndexedDB: Open/Create
var indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndex...
IndexedDB: Write/Read
open.onsuccess = function() {
var db = open.result;
var tx = db.transaction("FancyNamedStore", "read...
localForage* FTW!
* or any other library…
„localForage is a JavaScript library that improves the
offline experience of your web app by using an
asynchronous data stor...
„localForage includes a localStorage-backed fallback
store for browsers with no IndexedDB or WebSQL
support. Asynchronous ...
„localForage offers a callback API as well as support
for the ES6 Promises API, so you can use
whichever you prefer.“
–http...
Modern Times
Image©byAppleComputerInc.
Service
Workers
— https://github.com/w3c/ServiceWorker
„Service workers are a new browser feature that
provide event-driven scripts that r...
— https://github.com/w3c/ServiceWorker
„Service workers also have scriptable caches. Along
with the ability to respond to ...
Introduction
☁🖥 Internet
1
2
☁🖥 Internet
📜Service Worker
1 2
3
☁
🖥
Internet
📜Service Worker
📁Cache
1
2
3
3
☁
🖥
Internet
📜Service Worker
📁Cache
5
3
2
4
1
☁
🖥
Internet
📜Service Worker
📁Cache
❌
1
2
3
4
Code
Register Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/s...
Service Worker Overview
self.addEventListener('install', function(event) {
console.log("installed");
});
self.addEventList...
Install
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
retur...
Fetch
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(respon...
Fetch & Update Cache
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(...
Clean Up Cache
this.addEventListener('activate', function(event) {
var cacheWhitelist = ['v2'];
event.waitUntil(
caches.ke...
Update Cache
var CACHE_NAME = 'static-v9';
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open...
We have the tools!
GonzaloBaeza-https://flic.kr/p/dCPzuE
Now & The Future
Progressive
Web Apps
–Ada Rose Edwards
https://www.smashingmagazine.com/2016/09/the-building-blocks-of-progressive-web-apps/
„An ideal web app ...
OMG! PWA? WTF?
• Progressive
• Responsive
• Connectivity independent
• App-like
• Safe
• Discoverable
• Installable
• Link...
PWA Architecture
„Thorsten“-https://flic.kr/p/y3ib6k
App Shell
Service Workers
www.audio-luci-store.it-https://flic.kr/p/hQannE
Installability
Push Notification
• Allow SW to wake up
• Works in Background, only SW is woken up
• Needs permission from user!
–W3C
https://w3c.github.io/push-api/
„The Push API enables sending of a push message
to a webapp via a push service.“
And Webpages?
–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 sh...
Cache Data from APIs
• localStorage
• sessionStorage
• IndexedDB
Are you online?
var online = navigator.onLine;
if (!online) {
// Fallback -> Get Data from Storage!
}
else {
// Use networ...
That’s easy!
Wait?
• Slow network? (Edge, GPRS etc.)
• mobile networks are not reliable…
• „Lie“-Fi
Use Service Workers
• Provide offline fallback
• Cache static files
• Controll the network ;)
Demo
GPRS
GPRS + SW
Considerations
• Don't abuse offline caches.
• How to deal with sensitive information?
• Are my assets permanently stored?
...
Always on
is a lie.
Carsten Sandtner
@casarock
sandtner@mediaman.de
https://github.com/casarock
¯_(ツ)_/¯
Always on! ... or not?
Always on! ... or not?
Always on! ... or not?
Always on! ... or not?
Upcoming SlideShare
Loading in …5
×

Always on! ... or not?

275 views

Published on

My Slides for my Talk about being Always On is a lie and how developers could add improvements to their web site to deliver a great experience even when the network is flaky!

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// Gesellschaft für Kommunikation mbH
  2. 2. about:me Carsten Sandtner @casarock Head of Software Development //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. AppCache: Definition <!DOCTYPE html> <html lang="en" manifest="cache.manifest">
  10. 10. AppCache: Manifest CACHE MANIFEST # v2 2016-09-30 index.html cache.html style.css app.js hero.png # Use from network if available NETWORK: network.html # Fallback content FALLBACK: / fallback.html
  11. 11. AppCache: Javascript window.applicationCache.onchecking = function(e) {} window.applicationCache.onnoupdate = function(e) {} window.applicationCache.onupdateready = function(e) {} window.applicationCache.onobsolete = function(e) {} window.applicationCache.ondownloading = function(e) {} window.applicationCache.oncached = function(e) {} window.applicationCache.onerror = function(e) {} window.applicationCache.onprogress = function(e) {}
  12. 12. The TRUTH
  13. 13. • 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 • …
  14. 14. – Jake Archibald http://alistapart.com/article/application-cache-is-a-douchebag „Application Cache is a Douchebag“
  15. 15. 2016 W3C decides to remove application cache from standard
  16. 16. AlexanderBoden-https://flic.kr/p/pMrQ1N Things are getting better
  17. 17. Web Storages
  18. 18. Web Storages • key/value store • localStorage • sessionStorage
  19. 19. 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));
  20. 20. 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));
  21. 21. WebStorages • easy to use! • good browser support! • But: • http/https define different stores! • asynchronous • Quota?
  22. 22. IndexedDB
  23. 23. –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.“
  24. 24. 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() {};
  25. 25. 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(); }; }
  26. 26. localForage* FTW! * or any other library…
  27. 27. „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
  28. 28. „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
  29. 29. „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
  30. 30. Modern Times Image©byAppleComputerInc.
  31. 31. Service Workers
  32. 32. — 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.“
  33. 33. — 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”.“
  34. 34. Introduction
  35. 35. ☁🖥 Internet 1 2
  36. 36. ☁🖥 Internet 📜Service Worker 1 2 3
  37. 37. ☁ 🖥 Internet 📜Service Worker 📁Cache 1 2 3 3
  38. 38. ☁ 🖥 Internet 📜Service Worker 📁Cache 5 3 2 4 1
  39. 39. ☁ 🖥 Internet 📜Service Worker 📁Cache ❌ 1 2 3 4
  40. 40. Code
  41. 41. 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); }); }
  42. 42. 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!!")); });
  43. 43. Install self.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ '/images/myImage.png', '/index.html' ]); }) ); });
  44. 44. Fetch this.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); });
  45. 45. 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'); }) ); });
  46. 46. 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); } })); }) ); });
  47. 47. 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); } })); }) ); });
  48. 48. We have the tools!
  49. 49. GonzaloBaeza-https://flic.kr/p/dCPzuE Now & The Future
  50. 50. Progressive Web Apps
  51. 51. –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.“
  52. 52. OMG! PWA? WTF? • Progressive • Responsive • Connectivity independent • App-like • Safe • Discoverable • Installable • Linkable
  53. 53. PWA Architecture „Thorsten“-https://flic.kr/p/y3ib6k
  54. 54. App Shell
  55. 55. Service Workers www.audio-luci-store.it-https://flic.kr/p/hQannE
  56. 56. Installability
  57. 57. Push Notification • Allow SW to wake up • Works in Background, only SW is woken up • Needs permission from user!
  58. 58. –W3C https://w3c.github.io/push-api/ „The Push API enables sending of a push message to a webapp via a push service.“
  59. 59. And Webpages?
  60. 60. –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.“
  61. 61. Cache Data from APIs • localStorage • sessionStorage • IndexedDB
  62. 62. Are you online? var online = navigator.onLine; if (!online) { // Fallback -> Get Data from Storage! } else { // Use network.... }
  63. 63. That’s easy!
  64. 64. Wait? • Slow network? (Edge, GPRS etc.) • mobile networks are not reliable… • „Lie“-Fi
  65. 65. Use Service Workers • Provide offline fallback • Cache static files • Controll the network ;)
  66. 66. Demo
  67. 67. GPRS
  68. 68. GPRS + SW
  69. 69. Considerations • Don't abuse offline caches. • How to deal with sensitive information? • Are my assets permanently stored? • Think about your use case!
  70. 70. Always on is a lie. Carsten Sandtner @casarock sandtner@mediaman.de https://github.com/casarock ¯_(ツ)_/¯

×