Skip to content

Instantly share code, notes, and snippets.

@jacky810124
jacky810124 / sw.js
Created March 22, 2018 15:38
PWA Day05 - fetch event
self.addEventListener('fetch', event => {
console.log('[Service Worker] - fetch event')
event.respondWith(
self
.caches
.match(event.request)
.then(result => {
if (result == null) {
return fetch(event.request)
@jacky810124
jacky810124 / app.js
Created March 28, 2018 11:25
PWA Day06 Cache On User Interaction
document
.querySelector('.cache-article')
.addEventListener('click', (event) => {
event.preventDefault()
const id = this.dataset.articleId
caches
.open('mysite-article-' + id)
.then((cache) => {
@jacky810124
jacky810124 / sw.js
Created March 28, 2018 12:04
PWA Day06 - on network response
self.addEventListener('fetch', function(event) {
event.respondWith(
self
.caches
.open('mysite-dynamic')
.then(function(cache) {
return cache
.match(event.request)
.then(function (response) {
if (response != null) {
@jacky810124
jacky810124 / sw.js
Created March 28, 2018 12:40
PWA Day06 - cache only
self.addEventListener('fetch', function(event) {
event.respondWith(caches.match(event.request))
})
@jacky810124
jacky810124 / sw.js
Created March 28, 2018 12:50
PWA Day06 - network only
self.addEventListener('fetch', function(event) {
event.respondWith(fetch(event.request))
})
@jacky810124
jacky810124 / sw.js
Created March 28, 2018 12:55
PWA Day 06 - cache falling back to network
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request)
})
)
})
@jacky810124
jacky810124 / sw.js
Created March 28, 2018 15:48
PWA Day 06 - network falling back to cache
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request)
})
)
})
@jacky810124
jacky810124 / app.js
Created March 29, 2018 06:38
PWA Day06 - cache then network
// Here is the code in the app.js:
var networkDataReceived = false
startSpinner()
// fetch fresh data
var networkUpdate = fetch('/data.json')
.then(function(response) {
return response.json()
})
@jacky810124
jacky810124 / sw.js
Created March 29, 2018 06:46
PWA Day06 - cache then network
// Here is the code in the sw.js:
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())
@jacky810124
jacky810124 / sw.js
Created March 29, 2018 06:58
PWA Day06 - generic fallback
self.addEventListener('fetch', function(event) {
event.respondWith(
// Try the cache
caches
.match(event.request)
.then(function(response) {
// Fall back to network
return response || fetch(event.request)
})
.catch(function() {