作为 PWA 的象征之一,我们首先做的,就是加上 Service Worker。
添加 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:

本文详细介绍了如何在项目中引入ServiceWorker以提升用户体验,包括注册流程、缓存策略的设定及离线访问的支持。
最低0.47元/天 解锁文章
987

被折叠的 条评论
为什么被折叠?



