案例地址:https://zhangxinxu.github.io/https-demo/cache/start.html
我们直接看一个例子吧,如下HTML和JS代码:
<h3>一些提示信息</h3>
<ul>
<li>浏览器是否支持:<span id="isSupport"></span></li>
<li>service worker是否注册成功:<span id="isSuccess"></span></li>
<li>当前注册状态:<span id="state"></span></li>
<li>当前service worker状态:<span id="swState"></span></li>
</ul>
<script src="./static/jquery.min.js"></script>
<script>
if (‘serviceWorker‘ in navigator) {
$(‘#isSupport‘).text(‘支持‘);
// 开始注册service workers
navigator.serviceWorker.register(‘./sw-demo-cache.js‘, {
scope: ‘./‘
}).then(function (registration) {
$(‘#isSuccess‘).text(‘注册成功‘);
var serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
$(‘#state‘).text(‘installing‘);
} else if (registration.waiting) {
serviceWorker = registration.waiting;
$(‘#state‘).text(‘waiting‘);
} else if (registration.active) {
serviceWorker = registration.active;
$(‘#state‘).text(‘active‘);
}
if (serviceWorker) {
$(‘#swState‘).text(serviceWorker.state);
serviceWorker.addEventListener(‘statechange‘, function (e) {
$(‘#swState‘).append(‘ 状态变化为‘ + e.target.state);
});
}
}).catch (function (error) {
$(‘#isSuccess‘).text(‘注册没有成功‘);
});
} else {
$(‘#isSupport‘).text(‘不支持‘);
}
</script>
sw-demo-cache.js这个JS中复制如下代码:
var VERSION = ‘v1‘;
// 缓存
self.addEventListener(‘install‘, function(event) {
event.waitUntil(
caches.open(VERSION).then(function(cache) {
return cache.addAll([
‘./start.html‘,
‘./static/jquery.min.js‘,
‘./static/mm1.jpg‘
]);
})
);
});
// 缓存更新
self.addEventListener(‘activate‘, function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
// 如果当前版本和缓存版本不一致
if (cacheName !== VERSION) {
return caches.delete(cacheName);
}
})
);
})
);
});
// 捕获请求并返回缓存数据
self.addEventListener(‘fetch‘, function(event) {
event.respondWith(caches.match(event.request).catch(function() {
return fetch(event.request);
}).then(function(response) {
caches.open(VERSION).then(function(cache) {
cache.put(event.request, response);
});
return response.clone();
}).catch(function() {
return caches.match(‘./static/mm1.jpg‘);
}));
});原文:https://www.cnblogs.com/xieyongbin/p/10514729.html