SlideShare a Scribd company logo
Working with Data in
Service Workers
The PWA Pillars
Performance
Offline Scenarios
User Experience
Working with Data in
Service Workers
About Me
• sparXys CEO and senior consultant
• Microsoft MVP in the last 9 years
• Pro Single Page Application Development (Apress)
co-author
• 4 Microsoft Official Courses (MOCs) co-author
• GDG Rishon and AngularUP co-organizer
Agenda
• Storing data in the browser
• IndexedDB
• Storing data in service workers
Storing Data in The Browser
• Cookies
• Super small storage, string based, API not friendly
• Web Storage (localStorage / sessionStorage)
• String based dictionary, synchronous API
• Web SQL database
• Deprecated for years!
Enter IndexedDB
IndexedDB
• Advanced key-value data management
IndexedDB
Front-end
App
Fast
Reliable
Limited capacity
Local access only
Information loss
IndexedDB – The Database
Database
objectStore
Cursor on
objectStore
key : value
key : value
key : value
Index
Cursor on
index
IndexedDB API
• Very massive!
• Asynchronous
• Important note: synchronous APIs were deprecated by
W3C
• Exposed through window.indexedDB object
DEMO: IndexedDB in
Action
Working with Data in Service Workers
IndexedDB – Open the Database
var db;
var request = window.indexedDB.open("dbName");
request.onerror = function(event) {
…
};
request.onsuccess = function(event) {
db = request.result;
};
IndexedDB – Creating an
objectStore
var request = indexedDB.open(‘dbName’, 2);
request.onupgradeneeded = function(event) {
// Create an objectStore to hold information about customers.
var objectStore = db.createObjectStore("products", { keyPath: "id" });
// Create an index to search customers by name.
objectStore.createIndex("name", "name", { unique: false });
};
IndexedDB – Creating a
Transaction
var transaction = db.transaction(["products"], "readwrite");
transaction.oncomplete = function(event) { … };
transaction.onerror = function(event) { … };
// will add the object into the objectStore
var objectStore = transaction.objectStore("products");
var request = objectStore.add({ id: 7, name: "IndexedDB" });
request.onsuccess = function(event) {
// event.target.result == object.id
}
IndexedDB – Using a Cursor
var transaction = db.transaction(["products"]);
var objectStore = transaction.objectStore("products");
var cursor = objectStore.openCursor();
cursor.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
…
cursor.continue();
} else {
console.log("No entries");
}
};
IndexedDB – Working with
Indexes
var transaction = db.transaction(["products"]);
var objectStore = transaction.objectStore("products");
var index = objectStore.index("name");
var request = index.get("John");
request.onsuccess = function(event) { … };
DEMO: Let’s Code with
IndexedDB
Where IndexedDB Shines?
• Data driven scenarios
• As a hybrid application database
• Combined with service workers
• Or for any other offline scenarios
Combining IndexedDB and Service
Workers
• IndexedDB is currently the only way to store data in
service workers secanrio
• Combining Cache API and IndexedDB in service
worker can satisfy PWA offline guidelines
Guidelines for Storing Data in
Service Worker Scenario
Cache API
• Static resources
IndexedDB
• Dynamic data (JSON)
{
“id”: “1”,
“name”: “name”,
“price”: “20”
}
Storing Data Locally
App
Network
IndexedDB
Cache
JSON
Resources
Working with Service Workers
Events
• When service worker activates
• Create the database if needed
var db;
function createDB() {
var request = indexedDB.open(‘dbName’, 1);
/// wire into upgradeneeded event and create the db
}
self.addEventListener('activate', function(event) {
event.waitUntil(createDB());
});
Working with Service Workers
Events – Cont.
• When service worker installs
• Cache resources
function cacheResources() {
return caches.open('cacheV1').then(function(cache) {
return cache.addAll([ … ]); // array of resource urls
});
}
self.addEventListener('install', function(event) {
event.waitUntil(cacheResources());
});
Offline Scenarios
App
Network
IndexedDB
Cache
JSON
Resources
Demo: Storing Data in
Service Worker
Syncing To The Server
• Background sync and periodic background sync
• Sync data when there is connectivity or periodicly
• Non standard – available only in Chrome
• The online/offline events and navigator.onLine
property
Online/Offline events Example
window.addEventListener(‘DOMContentLoaded', function() {
function syncIfNeeded(event) {
// implement
}
function switchToOffline(event) {
// implement
}
window.addEventListener('online’, syncIfNeeded);
window.addEventListener('offline’, switchToOffline);
});
Summary
• IndexedDB is a full blown database in your app’s
front-end
• It can help you to persist your front-end data
• IndexedDB is suitable for offline scenarios
Resources
• IndexedDB on MDN - http://mzl.la/1u1sngQ
• Free online PWA course -
https://developers.google.com/web/ilt/pwa/
• My Website – http://www.gilfink.net
• Follow me on Twitter – @gilfink
Thank You!

More Related Content

Working with Data in Service Workers

  • 1. Working with Data in Service Workers
  • 6. Working with Data in Service Workers
  • 7. About Me • sparXys CEO and senior consultant • Microsoft MVP in the last 9 years • Pro Single Page Application Development (Apress) co-author • 4 Microsoft Official Courses (MOCs) co-author • GDG Rishon and AngularUP co-organizer
  • 8. Agenda • Storing data in the browser • IndexedDB • Storing data in service workers
  • 9. Storing Data in The Browser • Cookies • Super small storage, string based, API not friendly • Web Storage (localStorage / sessionStorage) • String based dictionary, synchronous API • Web SQL database • Deprecated for years!
  • 11. IndexedDB • Advanced key-value data management IndexedDB Front-end App Fast Reliable Limited capacity Local access only Information loss
  • 12. IndexedDB – The Database Database objectStore Cursor on objectStore key : value key : value key : value Index Cursor on index
  • 13. IndexedDB API • Very massive! • Asynchronous • Important note: synchronous APIs were deprecated by W3C • Exposed through window.indexedDB object
  • 16. IndexedDB – Open the Database var db; var request = window.indexedDB.open("dbName"); request.onerror = function(event) { … }; request.onsuccess = function(event) { db = request.result; };
  • 17. IndexedDB – Creating an objectStore var request = indexedDB.open(‘dbName’, 2); request.onupgradeneeded = function(event) { // Create an objectStore to hold information about customers. var objectStore = db.createObjectStore("products", { keyPath: "id" }); // Create an index to search customers by name. objectStore.createIndex("name", "name", { unique: false }); };
  • 18. IndexedDB – Creating a Transaction var transaction = db.transaction(["products"], "readwrite"); transaction.oncomplete = function(event) { … }; transaction.onerror = function(event) { … }; // will add the object into the objectStore var objectStore = transaction.objectStore("products"); var request = objectStore.add({ id: 7, name: "IndexedDB" }); request.onsuccess = function(event) { // event.target.result == object.id }
  • 19. IndexedDB – Using a Cursor var transaction = db.transaction(["products"]); var objectStore = transaction.objectStore("products"); var cursor = objectStore.openCursor(); cursor.onsuccess = function(event) { var cursor = event.target.result; if (cursor) { … cursor.continue(); } else { console.log("No entries"); } };
  • 20. IndexedDB – Working with Indexes var transaction = db.transaction(["products"]); var objectStore = transaction.objectStore("products"); var index = objectStore.index("name"); var request = index.get("John"); request.onsuccess = function(event) { … };
  • 21. DEMO: Let’s Code with IndexedDB
  • 22. Where IndexedDB Shines? • Data driven scenarios • As a hybrid application database • Combined with service workers • Or for any other offline scenarios
  • 23. Combining IndexedDB and Service Workers • IndexedDB is currently the only way to store data in service workers secanrio • Combining Cache API and IndexedDB in service worker can satisfy PWA offline guidelines
  • 24. Guidelines for Storing Data in Service Worker Scenario Cache API • Static resources IndexedDB • Dynamic data (JSON) { “id”: “1”, “name”: “name”, “price”: “20” }
  • 26. Working with Service Workers Events • When service worker activates • Create the database if needed var db; function createDB() { var request = indexedDB.open(‘dbName’, 1); /// wire into upgradeneeded event and create the db } self.addEventListener('activate', function(event) { event.waitUntil(createDB()); });
  • 27. Working with Service Workers Events – Cont. • When service worker installs • Cache resources function cacheResources() { return caches.open('cacheV1').then(function(cache) { return cache.addAll([ … ]); // array of resource urls }); } self.addEventListener('install', function(event) { event.waitUntil(cacheResources()); });
  • 29. Demo: Storing Data in Service Worker
  • 30. Syncing To The Server • Background sync and periodic background sync • Sync data when there is connectivity or periodicly • Non standard – available only in Chrome • The online/offline events and navigator.onLine property
  • 31. Online/Offline events Example window.addEventListener(‘DOMContentLoaded', function() { function syncIfNeeded(event) { // implement } function switchToOffline(event) { // implement } window.addEventListener('online’, syncIfNeeded); window.addEventListener('offline’, switchToOffline); });
  • 32. Summary • IndexedDB is a full blown database in your app’s front-end • It can help you to persist your front-end data • IndexedDB is suitable for offline scenarios
  • 33. Resources • IndexedDB on MDN - http://mzl.la/1u1sngQ • Free online PWA course - https://developers.google.com/web/ilt/pwa/ • My Website – http://www.gilfink.net • Follow me on Twitter – @gilfink