查看效果:https://cnj8.com/index.html
怎么操作?
1、html端加入
2、sw.js
const CACHE_NAME = 'lc999';self.addEventListener('install', event => {});self.addEventListener('fetch', event => { if (event.request.method != 'GET') return false; event.respondWith(caches.match(event.request).then(response => { if (response) return response; return fetch(event.request).then(response => { if (!response.ok) return response; const newResponse = response.clone(); if(event.request.url.indexOf("http")===0){ caches.open(CACHE_NAME).then(cache => cache.put(event.request, newResponse)); } return response; }); })); });
3、需要及时更新的网页中加入
const CACHE_NAME = 'lc999';
if ('serviceWorker' in navigator) {fetch(location.href + '?&t=' + Math.round(Number(new Date()) / 120000), {cache: "no-cache"}).then(response => {if (response.ok){const newResponse = response.clone();caches.open(CACHE_NAME).then(cache => cache.put(location.href, newResponse));}}); }
总结:3步实现,浏览一次,断网可用,有网自动更新,是不是很神奇?