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
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

What's hot

What's hot (20)

I3 - Running SharePoint 2016 in Azure the do's and dont's - Jasjit Chopra
I3 - Running SharePoint 2016 in Azure the do's and dont's - Jasjit ChopraI3 - Running SharePoint 2016 in Azure the do's and dont's - Jasjit Chopra
I3 - Running SharePoint 2016 in Azure the do's and dont's - Jasjit Chopra
 
Getting started with Azure Cognitive services
Getting started with Azure Cognitive servicesGetting started with Azure Cognitive services
Getting started with Azure Cognitive services
 
Database Choices
Database ChoicesDatabase Choices
Database Choices
 
Test driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDBTest driving Azure Search and DocumentDB
Test driving Azure Search and DocumentDB
 
TechDays NL 2016 - Building your scalable secure IoT Solution on Azure
TechDays NL 2016 - Building your scalable secure IoT Solution on AzureTechDays NL 2016 - Building your scalable secure IoT Solution on Azure
TechDays NL 2016 - Building your scalable secure IoT Solution on Azure
 
Azure Big Data Story
Azure Big Data StoryAzure Big Data Story
Azure Big Data Story
 
When Windows Apps meet SharePoint
When Windows Apps meet SharePointWhen Windows Apps meet SharePoint
When Windows Apps meet SharePoint
 
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
SharePoint Framework, React, and Office UI Fabric spc adriatics 2016
 
Azure DocumentDB for Healthcare Integration - Part 2
Azure DocumentDB for Healthcare Integration - Part 2Azure DocumentDB for Healthcare Integration - Part 2
Azure DocumentDB for Healthcare Integration - Part 2
 
Cool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDBCool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDB
 
CData - Triangle Woodard Group - QuickBooks
CData - Triangle Woodard Group - QuickBooksCData - Triangle Woodard Group - QuickBooks
CData - Triangle Woodard Group - QuickBooks
 
Bleeding Edge Databases
Bleeding Edge DatabasesBleeding Edge Databases
Bleeding Edge Databases
 
I2 - SharePoint Hybrid Search Start to Finish - Thomas Vochten
I2 - SharePoint Hybrid Search Start to Finish - Thomas VochtenI2 - SharePoint Hybrid Search Start to Finish - Thomas Vochten
I2 - SharePoint Hybrid Search Start to Finish - Thomas Vochten
 
Adobe Spark Meetup - 9/19/2018 - San Jose, CA
Adobe Spark Meetup - 9/19/2018 - San Jose, CAAdobe Spark Meetup - 9/19/2018 - San Jose, CA
Adobe Spark Meetup - 9/19/2018 - San Jose, CA
 
Introduction to Azure Search
Introduction to Azure SearchIntroduction to Azure Search
Introduction to Azure Search
 
Azure documentDB and Azure Search
Azure documentDB and Azure SearchAzure documentDB and Azure Search
Azure documentDB and Azure Search
 
Icinga Camp Bangalore - Icinga and Icinga Director
Icinga Camp Bangalore - Icinga and Icinga Director Icinga Camp Bangalore - Icinga and Icinga Director
Icinga Camp Bangalore - Icinga and Icinga Director
 
Securing an Azure Function REST API with Azure Active Directory
Securing an Azure Function REST API with Azure Active DirectorySecuring an Azure Function REST API with Azure Active Directory
Securing an Azure Function REST API with Azure Active Directory
 
Rev Your Engines: SharePoint Performance Best Practices
Rev Your Engines: SharePoint Performance Best PracticesRev Your Engines: SharePoint Performance Best Practices
Rev Your Engines: SharePoint Performance Best Practices
 
ArcGIS Open Data - Best Practices
ArcGIS Open Data - Best PracticesArcGIS Open Data - Best Practices
ArcGIS Open Data - Best Practices
 

Similar to Working with Data in Service Workers

oracle adf training | oracle adf course | oracle adf certification training
oracle adf training | oracle adf course | oracle adf certification training oracle adf training | oracle adf course | oracle adf certification training
oracle adf training | oracle adf course | oracle adf certification training
Nancy Thomas
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
Steven Francia
 
ArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQLArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQL
ArangoDB Database
 

Similar to Working with Data in Service Workers (20)

Who's afraid of front end databases
Who's afraid of front end databasesWho's afraid of front end databases
Who's afraid of front end databases
 
When to Use MongoDB
When to Use MongoDBWhen to Use MongoDB
When to Use MongoDB
 
oracle adf training | oracle adf course | oracle adf certification training
oracle adf training | oracle adf course | oracle adf certification training oracle adf training | oracle adf course | oracle adf certification training
oracle adf training | oracle adf course | oracle adf certification training
 
Web Applications Development with MEAN Stack
Web Applications Development with MEAN StackWeb Applications Development with MEAN Stack
Web Applications Development with MEAN Stack
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
 
Wmware NoSQL
Wmware NoSQLWmware NoSQL
Wmware NoSQL
 
Azure document db/Cosmos DB
Azure document db/Cosmos DBAzure document db/Cosmos DB
Azure document db/Cosmos DB
 
Introduction to Azure DocumentDB
Introduction to Azure DocumentDBIntroduction to Azure DocumentDB
Introduction to Azure DocumentDB
 
SQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The MoveSQL To NoSQL - Top 6 Questions Before Making The Move
SQL To NoSQL - Top 6 Questions Before Making The Move
 
ArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQLArangoDB – A different approach to NoSQL
ArangoDB – A different approach to NoSQL
 
5 Comparing Microsoft Big Data Technologies for Analytics
5 Comparing Microsoft Big Data Technologies for Analytics5 Comparing Microsoft Big Data Technologies for Analytics
5 Comparing Microsoft Big Data Technologies for Analytics
 
[WITH THE VISION 2017] IoT/AI時代を生き抜くためのデータ プラットフォーム (Leveraging Azure Data Se...
[WITH THE VISION 2017] IoT/AI時代を生き抜くためのデータ プラットフォーム (Leveraging Azure Data Se...[WITH THE VISION 2017] IoT/AI時代を生き抜くためのデータ プラットフォーム (Leveraging Azure Data Se...
[WITH THE VISION 2017] IoT/AI時代を生き抜くためのデータ プラットフォーム (Leveraging Azure Data Se...
 
Introducing DocumentDB
Introducing DocumentDB Introducing DocumentDB
Introducing DocumentDB
 
Oracle adf online training
Oracle adf online trainingOracle adf online training
Oracle adf online training
 
Big Data and NoSQL for Database and BI Pros
Big Data and NoSQL for Database and BI ProsBig Data and NoSQL for Database and BI Pros
Big Data and NoSQL for Database and BI Pros
 
Introducing NoSQL and MongoDB to complement Relational Databases (AMIS SIG 14...
Introducing NoSQL and MongoDB to complement Relational Databases (AMIS SIG 14...Introducing NoSQL and MongoDB to complement Relational Databases (AMIS SIG 14...
Introducing NoSQL and MongoDB to complement Relational Databases (AMIS SIG 14...
 
Why BaaS is crucial to early stage startups
Why BaaS is crucial to early stage startupsWhy BaaS is crucial to early stage startups
Why BaaS is crucial to early stage startups
 
Business objects data services advanced
Business objects data services advancedBusiness objects data services advanced
Business objects data services advanced
 
QuerySurge Slide Deck for Big Data Testing Webinar
QuerySurge Slide Deck for Big Data Testing WebinarQuerySurge Slide Deck for Big Data Testing Webinar
QuerySurge Slide Deck for Big Data Testing Webinar
 
DocumentDB - NoSQL on Cloud at Reboot2015
DocumentDB - NoSQL on Cloud at Reboot2015DocumentDB - NoSQL on Cloud at Reboot2015
DocumentDB - NoSQL on Cloud at Reboot2015
 

More from Gil Fink

More from Gil Fink (20)

Becoming a Tech Speaker
Becoming a Tech SpeakerBecoming a Tech Speaker
Becoming a Tech Speaker
 
Web animation on steroids web animation api
Web animation on steroids web animation api Web animation on steroids web animation api
Web animation on steroids web animation api
 
The Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has ArrivedThe Time for Vanilla Web Components has Arrived
The Time for Vanilla Web Components has Arrived
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has Arrived
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Being a tech speaker
Being a tech speakerBeing a tech speaker
Being a tech speaker
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
 
Redux data flow with angular
Redux data flow with angularRedux data flow with angular
Redux data flow with angular
 
One language to rule them all type script
One language to rule them all type scriptOne language to rule them all type script
One language to rule them all type script
 
End to-end apps with type script
End to-end apps with type scriptEnd to-end apps with type script
End to-end apps with type script
 
Web component driven development
Web component driven developmentWeb component driven development
Web component driven development
 
Web components
Web componentsWeb components
Web components
 
Redux data flow with angular 2
Redux data flow with angular 2Redux data flow with angular 2
Redux data flow with angular 2
 
Biological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJSBiological Modeling, Powered by AngularJS
Biological Modeling, Powered by AngularJS
 
Biological modeling, powered by angular js
Biological modeling, powered by angular jsBiological modeling, powered by angular js
Biological modeling, powered by angular js
 
Web components the future is here
Web components   the future is hereWeb components   the future is here
Web components the future is here
 
One language to rule them all type script
One language to rule them all type scriptOne language to rule them all type script
One language to rule them all type script
 

Recently uploaded

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

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
  • 15.
  • 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