window.addEventListener(‘load’, function {
navigator.serviceWorker.register(‘/sw.js’)
.then(function(registration) {
console.log(‘SW registered: ‘, registration);
})
.catch(function(registrationError) {
console.log(‘SW registration failed: ‘, registrationError);
});
});
这段代码检查浏览器是否支持Service Worker,并在页面加载完成后注册一个名为`sw.js`的文件。注册成功后,Service Worker便开始在后台运行。

安装阶段与预缓存
Service Worker的生命周期从`install`事件开始。这是预缓存关键静态资源(如CSS、JS、图片)的理想时机。通过`event.waitUntil`方法,我们可以确保Service Worker在所有资源缓存完成之前不会进入下一阶段。
const CACHE_NAME = 'app-static-v1';
const urlsToCache = [
'/',
'/styles/main.css',
'/script/app.js',
'/images/logo.png'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
此代码定义了一个缓存名称和需要预缓存的URL列表。在安装事件中,我们打开指定的缓存,并将所有列出的资源添加到缓存中。
拦截请求与缓存策略
Service Worker最强大的功能之一是能够通过`fetch`事件拦截网络请求。我们可以在此实现各种缓存策略,决定如何响应请求。
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// 缓存命中则返回缓存,否则继续网络请求
if (response) {
return response;
return fetch(event.request);
);
});
这是最基本的“缓存优先”策略。Service Worker会先检查请求的资源是否已在缓存中,如果是则直接返回,否则继续向网络发起请求。
常用缓存策略详解
在实际应用中,我们需要根据资源类型选择合适的缓存策略。以下是几种常见的策略:
| 策略名称 | 适用场景 | 实现方式 |
|---|---|---|
| 缓存优先 | 不常变化的静态资源 | 先查缓存,命中则返回,否则请求网络并缓存 |
| 网络优先 | 需要最新数据的API请求 | 先请求网络,失败则回退到缓存 |
| 仅缓存 | 完全离线的核心资源 | 只从缓存中获取,不访问网络 |
| 仅网络 | 需要实时验证的数据 | 只从网络获取,不使用缓存 |
缓存优先策略实现
对于样式表、脚本等静态资源,通常采用缓存优先策略,确保快速加载。
self.addEventListener('fetch', function(event) {
if (event.request.url.includes('/static/')) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
return fetch(event.request).then(function(response) {
// 检查是否为有效响应
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
// 克隆响应,因为响应流只能消费一次
var responseToCache = response.clone;
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
});
缓存版本管理与更新
当应用更新时,我们需要管理缓存的版本,确保用户能够获取到最新的资源。通过`activate`事件,我们可以清理旧版本的缓存。
const CACHE_NAMES = ['app-static-v2', 'app-dynamic-v1'];
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys.then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (CACHE_NAMES.indexOf(cacheName) === -1) {
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
这段代码在Service Worker激活时,会遍历所有缓存,并删除不在当前有效缓存名称列表中的旧缓存。
高级缓存技巧
除了基本策略,还有一些高级技巧可以提升应用性能:
- 动态缓存:对API响应进行缓存,但设置较短的过期时间
- 缓存降级:当网络请求失败时,提供备用的缓存内容或离线页面
- 后台同步:在网络恢复后,同步在离线期间产生的操作
- 消息推送:通过Push API向用户发送通知
离线页面实现
当用户离线且请求的资源不在缓存中时,提供一个友好的离线页面是很好的用户体验。
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
return fetch(event.request).catch(function {
// 当网络请求失败时,返回离线页面
return caches.match('/offline.html');
});
})
);
});
调试与最佳实践
Service Worker的调试需要一些特殊技巧。Chrome DevTools的Application面板提供了专门的Service Worker调试工具。
调试提示:在开发过程中,可以勾选"Update on reload"选项,确保每次刷新页面时Service Worker都会更新。
最佳实践总结:
- 为不同类型的资源使用不同的缓存策略
- 合理设置缓存版本和清理机制
- 始终提供离线回退方案
- 在生产环境谨慎使用缓存,避免缓存污染
- 定期测试应用的离线功能
通过合理配置Service Worker的缓存策略,可以显著提升Web应用的性能和用户体验,特别是在网络条件不稳定的情况下。
内容均以整理官方公开资料,价格可能随活动调整,请以购买页面显示为准,如涉侵权,请联系客服处理。
本文由星速云发布。发布者:星速云。禁止采集与转载行为,违者必究。出处:https://www.67wa.com/134617.html