作为 PWA 的象征之一,我们首先做的,就是加上 Service Worker。
我们的项目是使用 ejs 在 webpack 阶段注入几个变量生成最后的 index.html 的,所以直接拿 index.ejs 动刀即可:
<body>
<div id="container"></div>
<script src="<%= bundle %>"></script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', {
scope: './'
}).then(function(registration) {
registration.onupdatefound = function() {
if (navigator.serviceWorker.controller) {
const installingWorker = registration.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
break;
case 'redundant':
throw new Error('The installing ' +
'service worker became redundant.');
default:
// Ignore
}
};
}
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
} else {
console.log('service worker is not supported');
}
</script>
即 body 中,第二个 script 标签的内容,其参数 service-worker.js,是与 index.html 在同一个目录的空文件:
// This file is intentionally without code. // It's present so that service worker registration // will work when serving from the 'public' directory.
纳尼?这样就好了?
确实,这样,我们就已经完成了注册,这也是 PWA 和微信小程序这种二流方案不同的地方,其更注重于如何提高现有设计实现下的体验,使用开放的标准并进行推进。
再次运行 Lighthouse 后,发现我们的评分已经嗖嗖嗖上去了:
未完