中文静网的pwa代码分享,浏览一次,断网居然也可以访问
网页浏览一次后,把网线拔了,也能访问,pwa真的这么神奇吗?这个网站就实现了!
查看效果:https://cnj8.com/index.html
怎么操作?
1、html端加入
<script>if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js');}</script><link rel="manifest" href="/index.json">
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步实现,浏览一次,断网可用,有网自动更新,是不是很神奇?
查看效果:https://cnj8.com/index.html
怎么操作?
1、html端加入
<script>if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js');}</script><link rel="manifest" href="/index.json">
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步实现,浏览一次,断网可用,有网自动更新,是不是很神奇?