💓 博客主页:瑕疵的CSDN主页
📝 Gitee主页:瑕疵的gitee主页
⏩ 文章专栏:《热点资讯》
使用Service Worker实现离线应用
- 引言
- Service Worker 简介
- 注册和激活 Service Worker
- 注册 Service Worker
- 激活 Service Worker
- 缓存策略
- Cache-first 策略
- Network-first 策略
- Stale-while-revalidate 策略
- 实际案例
- 离线博客应用
- 最佳实践
- 缓存管理
- 错误处理
- 用户提示
- 总结
// register.js
if ('serviceWorker' in navigator) {window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js').then(registration => {console.log('Service Worker registered with scope:', registration.scope);}).catch(error => {console.log('Service Worker registration failed:', error);});});
}
// service-worker.js
self.addEventListener('install', event => {console.log('Service Worker installing...');event.waitUntil(caches.open('v1').then(cache => {return cache.addAll(['/','/index.html','/styles.css','/app.js']);}));
});self.addEventListener('activate', event => {console.log('Service Worker activating...');event.waitUntil(caches.keys().then(cacheNames => {return Promise.all(cacheNames.filter(cacheName => cacheName !== 'v1').map(cacheName => caches.delete(cacheName)));}));
});
Service Worker 可以通过不同的缓存策略来实现离线访问。常见的缓存策略包括: - **Cache-only**:仅从缓存中读取数据。 - **Network-only**:仅从网络中读取数据。 - **Cache-first**:先从缓存中读取数据,如果缓存中没有则从网络中读取。 - **Network-first**:先从网络中读取数据,如果网络请求失败则从缓存中读取。 - **Stale-while-revalidate**:先从缓存中读取数据,同时发起网络请求更新缓存。
self.addEventListener('fetch', event => {event.respondWith(caches.match(event.request).then(response => {return response || fetch(event.request);}));
});
self.addEventListener('fetch', event => {event.respondWith(fetch(event.request).catch(() => {return caches.match(event.request);}));
});
self.addEventListener('fetch', event => {event.respondWith(caches.open('v1').then(cache => {return cache.match(event.request).then(response => {const fetchPromise = fetch(event.request).then(networkResponse => {cache.put(event.request, networkResponse.clone());return networkResponse;});return response || fetchPromise;});}));
});
假设我们有一个简单的博客应用,需要实现离线访问功能。以下是实现步骤:
注册和激活 Service Worker
// register.js if ('serviceWorker' in navigator) {window.addEventListener('load', () => {navigator.serviceWorker.register('/service-worker.js').then(registration => {console.log('Service Worker registered with scope:', registration.scope);}).catch(error => {console.log('Service Worker registration failed:', error);});}); }
缓存静态资源
// service-worker.js self.addEventListener('install', event => {console.log('Service Worker installing...');event.waitUntil(caches.open('v1').then(cache => {return cache.addAll(['/','/index.html','/styles.css','/app.js','/images/logo.png']);})); });
处理网络请求
self.addEventListener('fetch', event => {event.respondWith(caches.match(event.request).then(response => {return response || fetch(event.request);})); });
更新 Service Worker
self.addEventListener('activate', event => {console.log('Service Worker activating...');event.waitUntil(caches.keys().then(cacheNames => {return Promise.all(cacheNames.filter(cacheName => cacheName !== 'v1').map(cacheName => caches.delete(cacheName)));})); });
Service Worker 可以通过不同的缓存策略来实现离线访问,显著提升用户体验。