SlideShare a Scribd company logo
1 of 32
PWA CACHING STRATEGIES
Gabriele Falasca
@gabrycaos
gabriele.falasca@sourcesense.com
PWA Caching Strategies – Gabriele Falasca
BREAKING NEWS!
Google announced that PWA can be distributed
through Play Store!!!
PWA Caching Strategies – Gabriele Falasca
WHAT IS PWA?
PWA Caching Strategies – Gabriele Falasca
PWA Caching Strategies – Gabriele Falasca
Migrate an existing webapp to pwa
1. HTTPS
2. THINK ABOUT CACHING
3. SERVICE WORKER
4. ADD TO HOMESCREEN
5. USE THE APIs YOU NEED
6. ENJOY
PWA Caching Strategies – Gabriele Falasca
SSR vs CSR recap
PWA Caching Strategies – Gabriele Falasca
SSR – Server Side Rendering
1. SERVER RETURNS A COMPLETE STATIC PAGE
2. PAGE LOADS REMOTE CSS, JS AND ASSETS
3. EVERY ACTION ON THE PAGE CAUSES A BROWSER
RELOAD
PWA Caching Strategies – Gabriele Falasca
CSR – CLIENT Side Rendering
1. SERVER RETURNS AN EMPTY PAGE (TEMPLATE)
2. JS MAKES REQUESTS TO GET PAGE CONTENT
3. EVERY ACTION ON THE PAGE RELOAD ONLY THE
DYNAMIC CONTENT
PWA Caching Strategies – Gabriele Falasca
SSR caching strategies
1. CACHE CSS JS AND ASSETS
2. IF THE APP HAS A STATIC PAGE, CACHE IT
TOO
PWA Caching Strategies – Gabriele Falasca
CSR caching strategies
1. CACHE CSS, JS, TEMPLATE AND ASSETS
2. CACHE DATA USING CACHE API OR INDEXEDDB
3. DETECT OFFLINE STATE THROUGH
JAVASCRIPT
PWA Caching Strategies – Gabriele Falasca
Detect offline state - JS
if(navigator.offline)
OR
navigator.addEventListener(‘offline’, …)
navigator.addEventListener(‘online’, …)
PWA Caching Strategies – Gabriele Falasca
SERVICE WORKERS
PWA Caching Strategies – Gabriele Falasca
What you can do with Service Workers?
1. CACHING THINGS
2. REGISTER FOR PUSH NOTIFICATION
3. USE VARIOUS API
4. AND MANY MANY MORE…
PWA Caching Strategies – Gabriele Falasca
App shell model
CACHING STRATEGIES
PWA Caching Strategies – Gabriele Falasca
CACHING STRATEGIES
When to cache resources?
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on install
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
console.log('caching App shell');
return cache.addAll([
'/static/js/main.chunk.js',
...pokemonImagesArray(),
]);
})
);
});
Ideal for: CSS, images, fonts, JS, templates… basically anything you'd consider static to that
"version" of your site.
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on activate
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
Ideal for: Clean-up & migration, or when you have to change your IndexedDb schema
YES, THERE IS A DB ALSO ON FRONTEND!
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on user interaction
document.querySelector(‘#cache-this!').addEventListener('click',
function(event) {
event.preventDefault();
var id = this.someDataset.articleId;
caches.open('mysite-article-' + id).then(function(cache) {
fetch('/get-article-urls?id=' + id).then(function(response) {
// /get-article-urls returns a JSON-encoded array of
// resource URLs that a given article depends on
return response.json();
}).then(function(urls) {
cache.addAll(urls);
});
});
});
Ideal for: “Read later”
Cache API is available not only in service workers!
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on network response
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Ideal for: To allow for efficient memory usage, you can only read a response/request's body once.
.clone() is used to create additional copies that can be read separately.
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on push message
self.addEventListener('push', function(event) {
if (event.data.text() == 'new-email') {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return fetch('/inbox.json').then(function(response) {
cache.put('/inbox.json', response.clone());
return response.json();
});
}).then(function(emails) {
registration.showNotification("New email", {
body: "From " + emails[0].from.name
tag: "new-email"
});
})
);
}
});
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
on background sync
self.addEventListener('sync', function(event) {
if (event.id == 'update-leaderboard') {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.add('/leaderboard.json');
})
);
}
});
Ideal for: Content relating to a notification, such as a chat message, a breaking news story, or an email. Also
infrequently changing content that benefits from immediate sync, such as a todo list update or a calendar
alteration.
PWA Caching Strategies – Gabriele Falasca
WHEN TO CACHE RESOURCES?
stale-while-revalidate
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function(response) {
var fetchPromise = fetch(event.request).then(function(networkResponse) {
cache.put(event.request, networkResponse.clone());
return networkResponse;
})
return response || fetchPromise;
})
})
);
});
If there's a cached version available, use it, but fetch an update for next time.
Ideal for: Frequently updating resources where having the very latest version is non-essential. Like avatars.
PWA Caching Strategies – Gabriele Falasca
CACHING STRATEGIES
Responding to requests
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
network only
self.addEventListener('fetch', function(event) {
event.respondWith(fetch(event.request));
// or simply don't call event.respondWith, which
// will result in default browser behaviour
});
Ideal for: Every non-GET request :)
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
cache, network fallback
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
Ideal for: If you're building offline-first, this is how you'll handle the majority of requests. Other patterns will be
exceptions based on the incoming request.
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
network, cache fallback
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request);
})
);
});
Ideal for: A quick-fix for resources that update frequently, outside of the "version" of the site. E.g. articles, avatars,
social media timelines, game leader boards
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
cache, then network
// IN THE PAGE
var networkDataReceived = false;
startSpinner();
// fetch fresh data
var networkUpdate = fetch('/data.json').then(function(response) {
return response.json();
}).then(function(data) {
networkDataReceived = true;
updatePage(data);
});
// fetch cached data
caches.match('/data.json').then(function(response) {
if (!response) throw Error("No data");
return response.json();
}).then(function(data) {
// don't overwrite newer network data
if (!networkDataReceived) {
updatePage(data);
}
}).catch(function() {
// we didn't get cached data, the network is our last hope:
return networkUpdate;
}).catch(showErrorMessage).then(stopSpinner);
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
cache, then network
// IN THE SERVICE WORKER
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
return fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
})
);
});
Ideal for: Content that updates frequently. E.g. articles, social media timelines, game leaderboards.
PWA Caching Strategies – Gabriele Falasca
RESPONDING TO REQUESTS
Other strategies
Cache and Network race
Generic fallback
PWA Caching Strategies – Gabriele Falasca
Questions?
PWA Caching Strategies – Gabriele Falasca
Thank You!

More Related Content

What's hot

(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...
(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...
(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...Amazon Web Services
 
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic Content
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic ContentCaching the Uncacheable: Leveraging Your CDN to Cache Dynamic Content
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic ContentFastly
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleStein Inge Morisbak
 
Stupid Boot Tricks: using ipxe and chef to get to boot management bliss
Stupid Boot Tricks: using ipxe and chef to get to boot management blissStupid Boot Tricks: using ipxe and chef to get to boot management bliss
Stupid Boot Tricks: using ipxe and chef to get to boot management blissmacslide
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019Matt Raible
 
Quarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationQuarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationCodeOps Technologies LLP
 
Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012Malcolm Box
 
Be Mean to your Code with Gauntlt #txlf 2013
Be Mean to your Code with Gauntlt #txlf 2013Be Mean to your Code with Gauntlt #txlf 2013
Be Mean to your Code with Gauntlt #txlf 2013James Wickett
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 
API analytics with Redis and Google Bigquery. NoSQL matters edition
API analytics with Redis and Google Bigquery. NoSQL matters editionAPI analytics with Redis and Google Bigquery. NoSQL matters edition
API analytics with Redis and Google Bigquery. NoSQL matters editionjavier ramirez
 
From Spring Boot 2.2 to Spring Boot 2.3 #jsug
From Spring Boot 2.2 to Spring Boot 2.3 #jsugFrom Spring Boot 2.2 to Spring Boot 2.3 #jsug
From Spring Boot 2.2 to Spring Boot 2.3 #jsugToshiaki Maki
 
Rugged by example with Gauntlt (Hacker Headshot)
Rugged by example with Gauntlt (Hacker Headshot)Rugged by example with Gauntlt (Hacker Headshot)
Rugged by example with Gauntlt (Hacker Headshot)James Wickett
 
Be Mean to Your Code - OWASP San Antonio
Be Mean to Your Code - OWASP San Antonio Be Mean to Your Code - OWASP San Antonio
Be Mean to Your Code - OWASP San Antonio James Wickett
 
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化Ryosuke Uchitate
 
決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話Ryosuke Uchitate
 
Antons Kranga Building Agile Infrastructures
Antons Kranga   Building Agile InfrastructuresAntons Kranga   Building Agile Infrastructures
Antons Kranga Building Agile InfrastructuresAntons Kranga
 
Production Readiness Strategies in an Automated World
Production Readiness Strategies in an Automated WorldProduction Readiness Strategies in an Automated World
Production Readiness Strategies in an Automated WorldSean Chittenden
 

What's hot (19)

(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...
(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...
(APP306) Using AWS CloudFormation for Deployment and Management at Scale | AW...
 
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic Content
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic ContentCaching the Uncacheable: Leveraging Your CDN to Cache Dynamic Content
Caching the Uncacheable: Leveraging Your CDN to Cache Dynamic Content
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 
Stupid Boot Tricks: using ipxe and chef to get to boot management bliss
Stupid Boot Tricks: using ipxe and chef to get to boot management blissStupid Boot Tricks: using ipxe and chef to get to boot management bliss
Stupid Boot Tricks: using ipxe and chef to get to boot management bliss
 
Iac d.damyanov 4.pptx
Iac d.damyanov 4.pptxIac d.damyanov 4.pptx
Iac d.damyanov 4.pptx
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
 
Quarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationQuarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java Application
 
ruxc0n 2012
ruxc0n 2012ruxc0n 2012
ruxc0n 2012
 
Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012Scaling Django for X Factor - DJUGL Oct 2012
Scaling Django for X Factor - DJUGL Oct 2012
 
Be Mean to your Code with Gauntlt #txlf 2013
Be Mean to your Code with Gauntlt #txlf 2013Be Mean to your Code with Gauntlt #txlf 2013
Be Mean to your Code with Gauntlt #txlf 2013
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 
API analytics with Redis and Google Bigquery. NoSQL matters edition
API analytics with Redis and Google Bigquery. NoSQL matters editionAPI analytics with Redis and Google Bigquery. NoSQL matters edition
API analytics with Redis and Google Bigquery. NoSQL matters edition
 
From Spring Boot 2.2 to Spring Boot 2.3 #jsug
From Spring Boot 2.2 to Spring Boot 2.3 #jsugFrom Spring Boot 2.2 to Spring Boot 2.3 #jsug
From Spring Boot 2.2 to Spring Boot 2.3 #jsug
 
Rugged by example with Gauntlt (Hacker Headshot)
Rugged by example with Gauntlt (Hacker Headshot)Rugged by example with Gauntlt (Hacker Headshot)
Rugged by example with Gauntlt (Hacker Headshot)
 
Be Mean to Your Code - OWASP San Antonio
Be Mean to Your Code - OWASP San Antonio Be Mean to Your Code - OWASP San Antonio
Be Mean to Your Code - OWASP San Antonio
 
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
Micrometerでメトリクスを収集してAmazon CloudWatchで可視化
 
決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話決済サービスのSpring Bootのバージョンを2系に上げた話
決済サービスのSpring Bootのバージョンを2系に上げた話
 
Antons Kranga Building Agile Infrastructures
Antons Kranga   Building Agile InfrastructuresAntons Kranga   Building Agile Infrastructures
Antons Kranga Building Agile Infrastructures
 
Production Readiness Strategies in an Automated World
Production Readiness Strategies in an Automated WorldProduction Readiness Strategies in an Automated World
Production Readiness Strategies in an Automated World
 

Similar to PWA caching strategies

Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPressTareq Hasan
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...andrewnacin
 
JQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayJQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayNatasha Rooney
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers TalkNatasha Rooney
 
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021StreamNative
 
Catalina.2013 03-05
Catalina.2013 03-05Catalina.2013 03-05
Catalina.2013 03-05NX21
 
Alfrescotomcat stderr.2013-03-05
Alfrescotomcat stderr.2013-03-05Alfrescotomcat stderr.2013-03-05
Alfrescotomcat stderr.2013-03-05NX21
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Longjaxconf
 
Distributed caching and computing v3.7
Distributed caching and computing v3.7Distributed caching and computing v3.7
Distributed caching and computing v3.7Rahul Gupta
 
Service workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsService workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsMukul Jain
 
Think Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayThink Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayRahul Gupta
 
Challenges when building high profile editorial sites
Challenges when building high profile editorial sitesChallenges when building high profile editorial sites
Challenges when building high profile editorial sitesYann Malet
 
Real World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker CachingReal World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker CachingChris Love
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
How we setup Rsync-powered Incremental Backups
How we setup Rsync-powered Incremental BackupsHow we setup Rsync-powered Incremental Backups
How we setup Rsync-powered Incremental Backupsnicholaspaun
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service WorkerAnna Su
 
How to develop Big Data Pipelines for Hadoop, by Costin Leau
How to develop Big Data Pipelines for Hadoop, by Costin LeauHow to develop Big Data Pipelines for Hadoop, by Costin Leau
How to develop Big Data Pipelines for Hadoop, by Costin LeauCodemotion
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources frameworkmarcplmer
 

Similar to PWA caching strategies (20)

PWA power
PWA powerPWA power
PWA power
 
Caching in WordPress
Caching in WordPressCaching in WordPress
Caching in WordPress
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
JQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayJQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On Vacay
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers Talk
 
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021
Simplifying Migration from Kafka to Pulsar - Pulsar Summit NA 2021
 
Catalina.2013 03-05
Catalina.2013 03-05Catalina.2013 03-05
Catalina.2013 03-05
 
Alfrescotomcat stderr.2013-03-05
Alfrescotomcat stderr.2013-03-05Alfrescotomcat stderr.2013-03-05
Alfrescotomcat stderr.2013-03-05
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Long
 
Distributed caching and computing v3.7
Distributed caching and computing v3.7Distributed caching and computing v3.7
Distributed caching and computing v3.7
 
Service workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsService workers and the role they play in modern day web apps
Service workers and the role they play in modern day web apps
 
Think Distributed: The Hazelcast Way
Think Distributed: The Hazelcast WayThink Distributed: The Hazelcast Way
Think Distributed: The Hazelcast Way
 
Challenges when building high profile editorial sites
Challenges when building high profile editorial sitesChallenges when building high profile editorial sites
Challenges when building high profile editorial sites
 
Real World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker CachingReal World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker Caching
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
How we setup Rsync-powered Incremental Backups
How we setup Rsync-powered Incremental BackupsHow we setup Rsync-powered Incremental Backups
How we setup Rsync-powered Incremental Backups
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service Worker
 
How to develop Big Data Pipelines for Hadoop, by Costin Leau
How to develop Big Data Pipelines for Hadoop, by Costin LeauHow to develop Big Data Pipelines for Hadoop, by Costin Leau
How to develop Big Data Pipelines for Hadoop, by Costin Leau
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources framework
 
EmbbededGF@JavaOneHyd
EmbbededGF@JavaOneHydEmbbededGF@JavaOneHyd
EmbbededGF@JavaOneHyd
 

Recently uploaded

➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...nirzagarg
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Delhi Call girls
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...kajalverma014
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...SUHANI PANDEY
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...nilamkumrai
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋nirzagarg
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445ruhi
 
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftAanSulistiyo
 
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...tanu pandey
 

Recently uploaded (20)

➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Pollachi 7001035870 Whatsapp Number, 24/07 Booking
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
6.High Profile Call Girls In Punjab +919053900678 Punjab Call GirlHigh Profil...
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
( Pune ) VIP Baner Call Girls 🎗️ 9352988975 Sizzling | Escorts | Girls Are Re...
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Himatnagar 7001035870 Whatsapp Number, 24/07 Booking
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
Microsoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck MicrosoftMicrosoft Azure Arc Customer Deck Microsoft
Microsoft Azure Arc Customer Deck Microsoft
 
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...Katraj ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For S...
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
 

PWA caching strategies

  • 1.
  • 2. PWA CACHING STRATEGIES Gabriele Falasca @gabrycaos gabriele.falasca@sourcesense.com
  • 3. PWA Caching Strategies – Gabriele Falasca BREAKING NEWS! Google announced that PWA can be distributed through Play Store!!!
  • 4. PWA Caching Strategies – Gabriele Falasca WHAT IS PWA?
  • 5. PWA Caching Strategies – Gabriele Falasca
  • 6. PWA Caching Strategies – Gabriele Falasca Migrate an existing webapp to pwa 1. HTTPS 2. THINK ABOUT CACHING 3. SERVICE WORKER 4. ADD TO HOMESCREEN 5. USE THE APIs YOU NEED 6. ENJOY
  • 7. PWA Caching Strategies – Gabriele Falasca SSR vs CSR recap
  • 8. PWA Caching Strategies – Gabriele Falasca SSR – Server Side Rendering 1. SERVER RETURNS A COMPLETE STATIC PAGE 2. PAGE LOADS REMOTE CSS, JS AND ASSETS 3. EVERY ACTION ON THE PAGE CAUSES A BROWSER RELOAD
  • 9. PWA Caching Strategies – Gabriele Falasca CSR – CLIENT Side Rendering 1. SERVER RETURNS AN EMPTY PAGE (TEMPLATE) 2. JS MAKES REQUESTS TO GET PAGE CONTENT 3. EVERY ACTION ON THE PAGE RELOAD ONLY THE DYNAMIC CONTENT
  • 10. PWA Caching Strategies – Gabriele Falasca SSR caching strategies 1. CACHE CSS JS AND ASSETS 2. IF THE APP HAS A STATIC PAGE, CACHE IT TOO
  • 11. PWA Caching Strategies – Gabriele Falasca CSR caching strategies 1. CACHE CSS, JS, TEMPLATE AND ASSETS 2. CACHE DATA USING CACHE API OR INDEXEDDB 3. DETECT OFFLINE STATE THROUGH JAVASCRIPT
  • 12. PWA Caching Strategies – Gabriele Falasca Detect offline state - JS if(navigator.offline) OR navigator.addEventListener(‘offline’, …) navigator.addEventListener(‘online’, …)
  • 13. PWA Caching Strategies – Gabriele Falasca SERVICE WORKERS
  • 14. PWA Caching Strategies – Gabriele Falasca What you can do with Service Workers? 1. CACHING THINGS 2. REGISTER FOR PUSH NOTIFICATION 3. USE VARIOUS API 4. AND MANY MANY MORE…
  • 15. PWA Caching Strategies – Gabriele Falasca App shell model CACHING STRATEGIES
  • 16. PWA Caching Strategies – Gabriele Falasca CACHING STRATEGIES When to cache resources?
  • 17. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on install self.addEventListener('install', function (event) { event.waitUntil( caches.open(CACHE_NAME).then(function (cache) { console.log('caching App shell'); return cache.addAll([ '/static/js/main.chunk.js', ...pokemonImagesArray(), ]); }) ); }); Ideal for: CSS, images, fonts, JS, templates… basically anything you'd consider static to that "version" of your site.
  • 18. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on activate self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.filter(function(cacheName) { // Return true if you want to remove this cache, // but remember that caches are shared across // the whole origin }).map(function(cacheName) { return caches.delete(cacheName); }) ); }) ); }); Ideal for: Clean-up & migration, or when you have to change your IndexedDb schema YES, THERE IS A DB ALSO ON FRONTEND!
  • 19. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on user interaction document.querySelector(‘#cache-this!').addEventListener('click', function(event) { event.preventDefault(); var id = this.someDataset.articleId; caches.open('mysite-article-' + id).then(function(cache) { fetch('/get-article-urls?id=' + id).then(function(response) { // /get-article-urls returns a JSON-encoded array of // resource URLs that a given article depends on return response.json(); }).then(function(urls) { cache.addAll(urls); }); }); }); Ideal for: “Read later” Cache API is available not only in service workers!
  • 20. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on network response self.addEventListener('fetch', function(event) { event.respondWith( caches.open(CACHE_NAME).then(function(cache) { return cache.match(event.request).then(function (response) { return response || fetch(event.request).then(function(response) { cache.put(event.request, response.clone()); return response; }); }); }) ); }); Ideal for: To allow for efficient memory usage, you can only read a response/request's body once. .clone() is used to create additional copies that can be read separately.
  • 21. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on push message self.addEventListener('push', function(event) { if (event.data.text() == 'new-email') { event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return fetch('/inbox.json').then(function(response) { cache.put('/inbox.json', response.clone()); return response.json(); }); }).then(function(emails) { registration.showNotification("New email", { body: "From " + emails[0].from.name tag: "new-email" }); }) ); } });
  • 22. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? on background sync self.addEventListener('sync', function(event) { if (event.id == 'update-leaderboard') { event.waitUntil( caches.open(CACHE_NAME).then(function(cache) { return cache.add('/leaderboard.json'); }) ); } }); Ideal for: Content relating to a notification, such as a chat message, a breaking news story, or an email. Also infrequently changing content that benefits from immediate sync, such as a todo list update or a calendar alteration.
  • 23. PWA Caching Strategies – Gabriele Falasca WHEN TO CACHE RESOURCES? stale-while-revalidate self.addEventListener('fetch', function(event) { event.respondWith( caches.open(CACHE_NAME).then(function(cache) { return cache.match(event.request).then(function(response) { var fetchPromise = fetch(event.request).then(function(networkResponse) { cache.put(event.request, networkResponse.clone()); return networkResponse; }) return response || fetchPromise; }) }) ); }); If there's a cached version available, use it, but fetch an update for next time. Ideal for: Frequently updating resources where having the very latest version is non-essential. Like avatars.
  • 24. PWA Caching Strategies – Gabriele Falasca CACHING STRATEGIES Responding to requests
  • 25. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS network only self.addEventListener('fetch', function(event) { event.respondWith(fetch(event.request)); // or simply don't call event.respondWith, which // will result in default browser behaviour }); Ideal for: Every non-GET request :)
  • 26. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS cache, network fallback self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); Ideal for: If you're building offline-first, this is how you'll handle the majority of requests. Other patterns will be exceptions based on the incoming request.
  • 27. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS network, cache fallback self.addEventListener('fetch', function(event) { event.respondWith( fetch(event.request).catch(function() { return caches.match(event.request); }) ); }); Ideal for: A quick-fix for resources that update frequently, outside of the "version" of the site. E.g. articles, avatars, social media timelines, game leader boards
  • 28. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS cache, then network // IN THE PAGE var networkDataReceived = false; startSpinner(); // fetch fresh data var networkUpdate = fetch('/data.json').then(function(response) { return response.json(); }).then(function(data) { networkDataReceived = true; updatePage(data); }); // fetch cached data caches.match('/data.json').then(function(response) { if (!response) throw Error("No data"); return response.json(); }).then(function(data) { // don't overwrite newer network data if (!networkDataReceived) { updatePage(data); } }).catch(function() { // we didn't get cached data, the network is our last hope: return networkUpdate; }).catch(showErrorMessage).then(stopSpinner);
  • 29. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS cache, then network // IN THE SERVICE WORKER self.addEventListener('fetch', function(event) { event.respondWith( caches.open('mysite-dynamic').then(function(cache) { return fetch(event.request).then(function(response) { cache.put(event.request, response.clone()); return response; }); }) ); }); Ideal for: Content that updates frequently. E.g. articles, social media timelines, game leaderboards.
  • 30. PWA Caching Strategies – Gabriele Falasca RESPONDING TO REQUESTS Other strategies Cache and Network race Generic fallback
  • 31. PWA Caching Strategies – Gabriele Falasca Questions?
  • 32. PWA Caching Strategies – Gabriele Falasca Thank You!

Editor's Notes

  1. Let’s start with a Breaking news, last week Google announced that PWA can be distributed through Play Store!!!
  2. progressive web apps are a hybrid of regular web pages (or websites) and a mobile application; is a webapplication that you can install on your mobile device like a native app
  3. You know it? :D today offline state is a problem for applications, today let’s analyze various use cases for managing user offline status
  4. For migrating an existing web application to Progressive web app you have to do the follow: make sure your website runs under https, otherwise yoru application doesn’t work, you have to think about caching, that is the object of this talk, you have to elaborate a strategiy for the best compromise for managing request, you have to choose cache versus network for punctual situations, you have to develop an «add to homescreen» button for mobile visualization, after that you have to use the apis you like in the serviceworker, and then you can enjoy with your webapp
  5. Before start i want to recap with you the difference between Server side Rendering and Client side rendering, you know?
  6. In a classic server side rendering scenario the server returns a complete static page, and after that the client make requests for static sassets; every action on the page causes the complete reload of the page
  7. Instead, in a client side rendering, the server return a blank page, or a blank template, and after the client fetch the resources and the dynamic content and build the page; in this case every action in the page causes only the reload of the section where action is triggered
  8. If you want to cache things in a SSR scenario you can cache only assets and static page, and you can handle offline state with Javascript
  9. If you want to cache things in a CSR scenario you can cache assets, static pages, and data using the cache api or indexedDB in case of complex data stractures, and you can handle offline state with Javascript
  10. If you want to manage the offline state with Javascript there are two ways: a check to the navigator.offline flag or other solution event based
  11. Do you know what is a Service worker? Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are used things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.
  12. A best practice for create a real offline experience is to use the App shell model; in this model you have to separate the App Shell from the content, App Shell is the scaffolding part of the application, header, menu main content space ecc.. The content is the dynamic data fetched from the network. In this model is easy to cache all the «static» part of the application treating the dynamic content separately.
  13. Okay, let’s see the use cases of this strategies in depth, starting to talk about when to cache resources
  14. First strategy for caching things is to cache it on Service Worker «install» event, this is ideal for caching dependencies and static assets, but not only, you can cache also data from network that is really static, for example a list that not change in the time
  15. Once a new ServiceWorker has installed & a previous version isn't being used, the new one activates, and you get an activate event. Because the old version is “deprecated”, it's a good time to handle schema migrations in IndexedDB and also delete unused caches.
  16. Ideal for give the user a "Read later" or "Save for offline" button. When it's clicked, fetch what you need from the network & pop it in the cache. As you can see the cache is available from pages as well as service workers, meaning you don't need to involve the service worker to add things to the cache.
  17. If a request doesn't match anything in the cache, get it from the network, send it to the page & add it to the cache at the same time. Be carefully using this strategies, because if the resource to fetch is too big there is a moment when you have a double copy in memory
  18. I don’t think i’ve to illustrate what push notification is, i want say only that they are supported out of the box from Service Workers. Thanks to it, we can make requests also when the app is closed, when arrives a push notification,if we can make request in this scenario, we can also cache the response of the request
  19. Another cool feature of service workers is the Background sync API (but be carefull, that is not standard API at today), is an api to manage the background sync of the data, also here, when is started the sync you can make requests and you can cache the response
  20. If there's a cached version available, use it, but fetch an update for next time. For example Whatsapp or Telegram Avatar, if an user change his profile photo, other users continue to see the old for a bunch of time, until the new photo is loaded.
  21. Now let's see what to do when the application made a network request, let’s see various use cases for choose cached data or network data, when is best to use one or anoter, and some hybrid approaches
  22. This is the simplest approach; as you can see, in Service Worker we can intercept the «fetch» event, trigger every time an app starts a request, in this case we simply return the request whitout do anything, this is the only approach for non-GET request, form submission, generic POST, PUT or DELETE call.
  23. Instead, this is the most used approach for the majority of generic GET requests, other patterns will be exeptions based on the incoming request, later let’s see a real Service Worker. This approach consists in check if exists a cached copy of that request, if not made the request on the network
  24. This is the old approach of the majority of social networks, I made the fetch request and show to the online user the last updates, but offilne users can see ever the cached version of their feed
  25. The newest approach of the social networks is this, i immediately show to the user the cached version of the data, then i made the network request and update the data on user feed, if the request fails there is no problem for the user
  26. The code in slide before is the part that you can write directly in the application, this is the part of the code that you have to write in the Service Worker
  27. There are other minor strategies for caching, Cache and Network race is an extreme use case, you can use this approach only if you are sure that the devices when the app will run have an extremely slow disk access, for using it you simply start the cache request and network request at the same time, and serve to the user the results obtained from the winner of this race, Generic Fallback is the classical page of error when is a problem :)