Skip to content

Instantly share code, notes, and snippets.

@masalib
Created August 11, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masalib/825f581da72d21ca18d15eff47e8e1b8 to your computer and use it in GitHub Desktop.
Save masalib/825f581da72d21ca18d15eff47e8e1b8 to your computer and use it in GitHub Desktop.
PWAとはサンプルソース7
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