更新中css
提示:在测试程序的时候尽可能使用Chrome的隐身模式,确保 Service Worker 不会从之前的残留状态中读取数据!!html
在sudo ng new pwa
新建工程以后,在工程的根目录上运行sudo ng add @angular/pwa
,此时就会自动添加Service Worker文件,Manifest.json文件和各类不一样尺寸的icon文件。 Angular PWA中文网传送门web
在app.component.ts
中引入import { SwUpdate } from '@angular/service-worker';
来加载SW的更新模块,每次PWA程序有更新均可以在这里使用SwUpdate模块获取更新,并使用以下代码可实现程序的更新操做:npm
export class AppComponent {
update: boolean;
constructor(updates: SwUpdate, private data: DataService) {
updates.available.subscribe( event => {
this.update = true;
updates.activateUpdate().then(() =>
document.location.reload()
);
}
);
}
title = 'PWA';
}
复制代码
SwUpdate文档传送门json
而后在html中使用一个*ngIf
来判断是否更新,(是则显示text,不是则不显示):api
<span *ngIf="update">There's an update associated with your progressive web application!</span>
复制代码
每次更新了程序都要从新build production程序,在根目录上运行sudo ng build --prod
,而后进入cd dist/PWA
,最后运行http-server -o
在服务器上运行更新后的程序。浏览器
因为 ng serve
对 Service Worker
无效,因此必须用一个独立的 HTTP 服务器在本地测试项目。 可使用任何 HTTP 服务器,我使用的是来自 npm 中的 http-server 包。固然也能够自定义端口以防止port冲突:缓存
http-server -p 8080 -c-1 dist/<project-name>
复制代码
注意: 若是想按期更新PWA,也就是使用interval建立一个周期轮询方法,须要先让应用注册Aervice worker的进程进入稳定状态,再让它开始执行轮询的过程,若是不断轮询更新(好比调用 interval())将阻止应用程序达到稳定态,也就永远不会往浏览器中注册 ServiceWorker 脚本。另外:应用中所执行的各类轮询都会阻止它达到稳定态服务器
constructor(appRef: ApplicationRef, updates: SwUpdate) {
// Allow the app to stabilize first, before starting polling for updates with `interval()`.
const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));
const everySixHours$ = interval(6 * 60 * 60 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);
everySixHoursOnceAppIsStable$.subscribe(() => updates.checkForUpdate());
}
复制代码
因此对于自动更新模块的使用总结:网络
constructor(appRef: ApplicationRef, updates: SwUpdate, private data: DataService) {
const appIsStable$ = appRef.isStable.pipe(first(isStable => isStable === true));
const everySixHours$ = interval(6 * 1000);
const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);
everySixHoursOnceAppIsStable$.subscribe(() => {
updates.checkForUpdate();
// console.log('check update in Service Worker');
});
updates.available.subscribe(event => {
console.log('gotta new version here', event.available);
updates.activateUpdate().then(() => document.location.reload());
});
}
复制代码
每6妙检测一次更新版本,若是没有updates.activateUpdate().then(() => document.location.reload());
则只是在检测到新版本时候提醒并不刷新并更新程序。 测试的时候须要从新ng build --prod
而后http-server -p 8080 -c-1 dist/PWA
从新运行http服务器,这时候在原来的页面上的console上就会发现出现了新版本的提醒。
(其实每次运行build命令都会出现版本更新不管是否更改代码,当应用的一个新的构建发布时,Service Worker 就把它看作此应用的一个新版本,版本是由 ngsw.json 文件的内容决定的,包含了全部已知内容的哈希值。 若是任何一个被缓存的文件发生了变化,则该文件的哈希也将在ngsw.json中随之变化,从而致使 Angular Service Worker 将这个活动文件的集合视为一个新版本)
全在nsgw-config.json
文件中定义PWA缓存,好比想缓存google的Montserrat字体和API地址,该文件中全部的代码形式都是glob格式,也就是:
好比:
在实际代码中这样作:
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
复制代码
在已经被建立的assetGroups
中添加:
"urls": [
"https://fonts.googleapis.com/**"
]
复制代码
AssetGroup遵循的TypeScript接口规则为:
interface AssetGroup {
name: string;
installMode?: 'prefetch' | 'lazy';
// prefetch 告诉 Angular Service Worker 在缓存当前版本的应用时要获取每个列出的资源。 这是个带宽密集型的模式,但能够确保这些资源在请求时可用,即便浏览器正处于离线状态
// lazy 不会预先缓存任何资源。相反,Angular Service Worker 只会缓存它收到请求的资源。 这是一种按需缓存模式。永远不会请求的资源也永远不会被缓存。 这对于像为不一样分辨率提供的图片之类的资源颇有用,那样 Service Worker 就只会为特定的屏幕和设备方向缓存正确的资源。
updateMode?: 'prefetch' | 'lazy';
// prefetch 会告诉 Service Worker 当即下载并缓存更新过的资源
// lazy 告诉 Service Worker 不要缓存这些资源,而是先把它们看做未被请求的,等到它们再次被请求时才进行更新。
lazy 这个 updateMode 只有在 installMode 也一样是 lazy 时才有效。
resources: {
files?: string[];
/** @deprecated As of v6 `versionedFiles` and `files` options have the same behavior. Use `files` instead. */
versionedFiles?: string[];
urls?: string[];
};
}
复制代码
在下方建立dataGroups
缓存API地址:
"dataGroups": [
{
"name": "jokes-api",
"urls": [
"https://api.chucknorris.io/jokes/random"
],
"cacheConfig": {
"strategy": "freshness",
"maxSize": 20,
"maxAge": "1h",
"timeout": "5s"
}
}
]
复制代码
dataGroups的配置遵循下面的接口:
export interface DataGroup {
name: string;
urls: string[];
version?: number;
cacheConfig: {
maxSize: number;
maxAge: string;
timeout?: string;
strategy?: 'freshness' | 'performance';
};
}
复制代码
其中的缓存设置中的几个项目分别是: