最近寫個小APP
想說沒網路也能用
沒想到也是一個大學問
舊的使用方法(以廢棄)
建議不用使用Using the application cache - HTML: HyperText Markup Language | MDN
以廢棄
使用參考
[HTML5試試看-25] 離線程式 - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
有趣的HTML5:离线存储 - SegmentFault 思否
sw
service worker 实现离线缓存
PWA-3小时带你实现渐进式WebAPP_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili
使用Service worker實現加速/離線訪問靜態blog網站_谷歌開發者 - 微文庫
實作
https://developers.google.com/web/fundamentals/codelabs/offline?hl=zh-tw
參照裡面做法
index.html
1 2 3 4 5 6 7
| <script> if('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') .then(function() { console.log("Service Worker Registered"); }); } </script>
|
sw.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| self.addEventListener('install', function(e) { console.log('[Service Worker] Install'); });
var cacheName = 'js13kPWA-v2'; var appShellFiles = [ '/', 'index.html', 'https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.0.1/html5-qrcode.min.js' ];
var contentToCache = appShellFiles;
self.addEventListener('install', function(e) { console.log('[Service Worker] Install'); e.waitUntil( caches.open(cacheName).then(function(cache) { console.log('[Service Worker] Caching all: app shell and content'); return cache.addAll(contentToCache); }) ); });
self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()); }); self.addEventListener('fetch', event => { event.respondWith( caches.open(cacheName) .then(cache => cache.match(event.request, {ignoreSearch: true})) .then(response => { return response || fetch(event.request); }) ); });
|
就順利成功
有空再深入研究