Created
August 11, 2018 11:07
-
-
Save masalib/825f581da72d21ca18d15eff47e8e1b8 to your computer and use it in GitHub Desktop.
PWAとはサンプルソース7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cacheName = 'v3'; | |
// インストールイベント | |
self.addEventListener('install',e => { | |
console.log('Service Worker: sw.js is Installed'); | |
}); | |
// アクティブイベント | |
self.addEventListener('activate',e => { | |
console.log('Service Worker: sw.js is Activater '); | |
e.waitUntil( | |
caches.keys().then(cacheNames => { | |
return Promise.all( | |
cacheNames.map(cache => { | |
if(cache !== cacheName){ | |
console.log('Service Worker: Clearing Old Cache'); | |
return caches.delete(cache); | |
} | |
}) | |
) | |
}) | |
); | |
}); | |
// Fetchイベント(横取り) | |
self.addEventListener('fetch',e => { | |
console.log('Service Worker: sw.js Fetching '); | |
e.respondWith( | |
fetch(e.request) | |
.then(res => { | |
//リクエストのコピーをする | |
const resClone = res.clone(); | |
//キャッシュを開く | |
caches | |
.open(cacheName) | |
.then(cache => { | |
cache.put(e.request, resClone); | |
}); | |
return res; | |
}).catch(err => caches.match(e.requset).then(res => res) ) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment