PWA之 Service worker lifecycle and cache management
一、register service worker
1. app.js 顶头添加:
if("serviceWorker" in navigator){ navigator.serviceWorker.register("/serviceworker.js") .then((registration)=>{ console.log(`Service Worker registered with scope ${registration.scope}`); }) .catch((err)=>{ console.log(`Service worker registration failed with ${err}`); }); }else{ console.log("service worker not found"); }
2. public文件夹下添加 serviceworker.js
3. npm start 运行后
二、logging request
sericeworker.js 中添加
self.addEventListener("fetch", (event)=>{ console.log(`fetch event for: ${event.request.url}`); });
运行后可以自动记录request
三、override request
self.addEventListener("fetch", (event)=>{ if(event.request.url.includes("bootstrap.min.css") ){ event.respondWith( new Response( `.hotel-slogan{background:green !important;} nav{display:none;}`, {"headers":{ "Content-Type":"text/css" }} ) ); } });
重写.css里面的background设置
四、fetch request 失败 => catch
self.addEventListener("fetch", (event)=>{ console.log(`fetch request for ${event.request.url}`); event.respondWith( fetch(event.request).catch(()=>{ return new Response(` Welcome to the Gotham imperial hotel<br /.> There seems to be a problem with your connection <br /> We look forward to serving you when you are online `, {headers:{ "Content-Type": "text/html" }}); }) ); });
手动中止程序后,刷新页面 =>
五、cache
1.
self.addEventListener("install", (event)=>{ event.waitUntil(caches.open("gih-cache").then((cache) =>{ return cache.add("/index-offline.html"); }) ); });
outcome:
2. 运用cache:
self.addEventListener("install", (event)=>{ event.waitUntil(caches.open("gih-cache").then((cache) =>{ return cache.add("/index-offline.html"); }) ); }); self.addEventListener("fetch", (event) =>{ event.respondWith( fetch(event.request).catch(()=>{ return caches.match("/index-offline.html"); }) ); });
outcome:
3. add all cache
const cachedPages = [ "/index-offline.html", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", "/css/gih-offline.css", "/img/jumbo-background-sm.jpg", "/img/logo-header.png" ]; self.addEventListener("install", (event)=>{ event.waitUntil(caches.open("gih-cache") .then((cache)=>{ return cache.addAll(cachedPages); })); });
outcome:
4. To serve from cache: We want to serve the file of the same name if it is there;Otherwise serve the offline content
把页面缓存下来,即使offline,也可以显示
const cachedPages = [ "/index-offline.html", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", "/css/gih-offline.css", "/img/jumbo-background-sm.jpg", "/img/logo-header.png" ]; self.addEventListener("install", (event)=>{ event.waitUntil(caches.open("gih-cache") .then((cache)=>{ return cache.addAll(cachedPages); })); }); self.addEventListener("fetch", (event)=>{ event.respondWith( fetch(event.request) .catch(()=>{ return caches.match(event.request) .then((response)=>{ if(response){ return response; }else{ return caches.match("/index-offline.html"); } }); }) ); });