关于 Service Worker 概念的例子,请参考我之前的这篇文章。本文是实战。
本地新建一个 html 文件,该文件里加载一个 Service worker 的实现:
<html>
<h1>Service Worker</h1>
<button onclick="Hello(event)">Click me</button>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('./sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
</script>
<script>
function Hello(event){
console.log(event);
}
</script>
</html>
该 HTML 加载的 Service Worker 实现,位于 sw.js 文件内:
// @ts-nocheck
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'/',
'/purehtml/serviceworker.html'
];
self.addEventListener('install', function(event) {
// Perform install steps
// @ts-ignore
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
console.log('Cache hit: ', response);
return response;
}
return fetch(event.request).then(
function(response) {
// Check if we received a valid response
if(!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache);
});
return response;
}
);
})
);
});
一定要把该 html 和 JavaScript,发布到 web server 上运行(比如使用 Node.js 的 express 框架)。
如果本地直接打开 HTML,会遇到错误:ServiceWorker registration failed:TypeError:failed to register a ServiceWorker:The URL protocol of the current origin('null') is not supported.
第一次在浏览器里访问该页面:
ServiceWorker registration successful with scope:
刷新之后,可以看到该应用的 Cache Storage 里,已经显示了两条缓存数据:
看到了处于 active 状态的 Service Worker:
如果一个网页是通过 Service Worker 返回的,在 Chrome 开发者工具里能看到对应的图标:
更多Jerry的原创文章,尽在:"汪子熙":
网友评论