Service Worker
重要通知
。
基本概况
Service worker 本质上充当 Web 应用程序、浏览器与网络(可用时)之间的代理服务器。这个 API 旨在创建有效的离线体验,它会拦截网络请求并根据网络是否可用来采取适当的动作、更新来自服务器的资源。它还提供入口以推送通知和访问后台同步 API。
- 官网:<>
- GitHub:<>
安装配置
使用示例
Service Workers
注意事项
- 出于安全原因,Service Workers 要求必须在 HTTPS 下才能运行。
- 为了便于本地开发,localhost 也被浏览器认为是安全源。
- 在 Firefox 浏览器的用户隐私模式,Service Worker 不可用。
官网:https://web.dev/progressive-web-apps/ 渐进式 Web 应用(PWA):https://developer.mozilla.org/zh-CN/docs/Web/Progressive_web_apps https://developer.mozilla.org/zh-CN/docs/Web/API/Service_Worker_API https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa https://www.html.cn/create-react-app/docs/making-a-progressive-web-app/ Web App Manifest:https://developer.mozilla.org/zh-CN/docs/Web/Manifest workbox:https://developer.chrome.com/docs/workbox/ 框架集成:https://developer.chrome.com/docs/workbox/framework-integrations/ https://developer.chrome.com/docs/workbox/migration/migrate-from-v4/#build_tool_option_overhaul vuecli3项目添加pwa支持:https://www.cnblogs.com/lcosima/p/14537877.html 渐进式加载:https://developer.mozilla.org/zh-CN/docs/Web/Progressive_web_apps/Loading
基本架构
注册服务
ServiceWorkerContainer.register(scriptURL, options)
.then(
function(registration) {
if (registration.installing) {
//
} else if (registration.waiting) {
//
} else if (registration.active) {
//
} else {
//
}
// registration.update();
}
).catch(
function(error) {
// do something
}
);
install过程
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
'/sw-test/style.css',
'/sw-test/app.js',
'/sw-test/gallery/',
'/sw-test/gallery/bountyHunters.jpg',
]);
})
);
});
自定义响应
this.addEventListener('fetch', function(event) {
// 对网络请求的资源和 cache 里可获取的资源进行匹配,查看是否缓存中有相应的资源
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request).then(function(response) {
return caches.open('v1').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
}).catch(function() {
// 异常时回退一些信息或相关资源
return caches.match('/sw-test/gallery/myLittleVader.jpg');
})
);
// 如果没有在缓存中找到匹配的资源,你可以告诉浏览器对着资源直接去 fetch 默认的网络请求
fetch(event.request)
// 如果没有在缓存中找到匹配的资源,同时网络也不可用,你可以用 match() 把一些回退的页面作为响应来匹配这些资源
caches.match('/fallback.html');
});
更新机制
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v2').then(function(cache) {
return cache.addAll([
'/sw-test/',
'/sw-test/index.html',
'/sw-test/style.css',
'/sw-test/app.js',
'/sw-test/image-list.js',
…
// include other new resources for the new version...
]);
})
);
});
activation过程
删除旧缓存
self.addEventListener('activate', function(event) {
var cacheWhitelist = ['v2'];
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (cacheWhitelist.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
缓存控制
一个域可以有多个命名 Cache 对象。你需要在你的脚本 (例如,在 ServiceWorker 中) 中处理缓存更新的方式。除非明确地更新缓存,否则缓存将不会被更新;除非删除,否则缓存数据不会过期。
数据存储
IndexedDB 可以在 service worker 内做数据存储,但是localStorage不可以,因为localStorage是同步机制。
PWA具体配置部署
PWA(Progressive Web App),即渐进式增强WEB应用
Reliable ( 可靠的 )、Fast( 快速的 )、Engaging( 可参与的)
Vue-cli3.0集成了PWA机制
注意事项
仅限于HTTPS,涉及安全性问题,因为需要权限较大。
部署PWA网站
配置HTTPS服务:网址必须是 https 协议,或者域名是 localhost
配置manifest.json:与index.html同级目录
Service Worker:主要用来做缓存,注册 Service Worker 并且监听 fetch 事件
sw.js:与index.html同级目录
在 index.html 中注册 sw.js
验证结果:打开Chrome浏览器查看右上角三个点,是否可以安装该WebAPP
manifest.json
Web 应用程序清单:https://developer.mozilla.org/zh-CN/docs/Web/Manifest
{
name: "", // 网站应用的全名。
short_name: "", // 显示在主屏上的短名字。
description: "", // 一两句话解释你的应用的用途。
icons: [ // 一串图标信息:源 URL,大小和类型。多包含几个图标,这样就能选中一个最适合用户设备的。
{
"src": "logo.png",
"sizes": "192x192",
"type": "image/png"
}
],
start_url: "", // 启动应用时打开的主页。
display: "", // 应用的显示方式;可以是 fullscreen、standalone、minimal-ui 或者 browser。
theme_color: "", // UI 主颜色,由操作系统使用。
background_color: "", // 背景色,用于安装和显示启动画面时。
}
{
"name": "PWA",
"short_name": "PWA-Example",
"id": "/",
"start_url": ".",
"display": "standalone",
"background_color": "#fff",
"description": "Progressive Web Apps,渐进式 Web 应用",
"icons": [{
"src": "images/touch/homescreen48.png",
"sizes": "48x48",
"type": "image/png"
}]
}
index.html
<link rel="manifest" href="/manifest.json">
<script>
if ('serviceWorker' in navigator) {
// load 事件完成之后才注册 service worker
window.addEventListener('load', function () {
// 注册 sw.js
navigator.serviceWorker.register('/service-worker.js', {scope: '/'})
.then(function (registration) {
// 注册成功
console.log('ServiceWorker registration successful');
})
.catch(function (err) {
// 注册失败
console.log('ServiceWorker registration failed');
});
});
}
</script>
service-worker.js
Chrome DevTools开发者工具
开始/暂停/调试 worker 的进程
- 打开地址,查看注册Service Workers的服务列表:chrome://serviceworker-internals

使用示例
改进优化
问题,改进思路,具体方案。