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
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"); } }); }) ); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。