html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="./index.css"/>
</head>
<body>
<div class="app">hello pwa</div>
<script>
navigator.serviceWorker.register('./sw.js',{
scope:'/'
}).then(registation=>{
console.log(registation)
},error=>{
console.log(error)
})
</script>
</body>
</html>
sw.js
const CACHE_NAME = 'cache_v2'
self.addEventListener('install',event=>{
console.log('install',event)
event.waitUntil(self.skipWaiting());
event.waitUntil(caches.open(CACHE_NAME).then(cache=>{
cache.addAll([
'/',
'./index.css'
])
}))
})
self.addEventListener('activate',event=>{
console.log('activate',event);
event.waitUntil(caches.keys().then(cachesNames=>{
return Promise.all(cachesNames.map(cacheName=>{
if(CACHE_NAME!==cacheName){
return caches.delete(cacheName);
}
}))
}))
})
self.addEventListener('fetch',event=>{
console.log('fetch',event);
event.respondWith(caches.open(CACHE_NAME).then(cache=>{
return cache.match(event.request).then(response=>{
if(response){
return response;
}
return fetch(event.request).then(response=>{
cache.put(event.request,response.clone());
return response;
})
})
}))
})