描述:
我们正在使用 sw precache 预先缓存脚本,因此要更新我们提供重新加载选项的脚本,因为我们正在监听 worker 消息以跳过等待新安装的 service worker 的未知原因,我们没有得到正确
导入脚本
// GETTING OLD SW reference (self) and NOT getting newly installed SW reference
self.addEventListener('message', function(event) {
*// not working*
self.skipWaiting();
});
// But if we put skipWaiting() in 'install' listener
// it is getting correct new SW reference and working correctly
self.addEventListener('install', function(event) {
// self.skipWaiting();
});
软件注册
if('serviceWorker' in window.navigator) {
window.addEventListener('load', function() {
window.navigator.serviceWorker.register("/serviceWorker.js").then(function(registration) {
console.log("ServiceWorker registration successful with scope: ", registration);
registration.onupdatefound = function() {
console.log('NEW WILD WORKER HAS SPAWNED.!', registration);
var installedWorker = registration.installing;
installedWorker.onstatechange = function() {
if (installedWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
console.log('Updated content is available RELOAD!', navigator.serviceWorker.controller);
var el = document.getElementById('feature');
el.style['display'] = 'block';
}
}
}
}
}).catch(function(error) {
console.error("ServiceWorker registration failed: ", error);
});
});
window.navigator.serviceWorker.addEventListener('controllerchange', function() {
console.log('SERVICE WORKER UPDATED');
});
}
网络包配置
new SWPrecacheWebpackPlugin({
cacheId: 'pwa',
filename: 'serviceWorker.js',
staticFileGlobsIgnorePatterns: [/\.map$/, /\.json$/, /_nch\.[0-9a-z]+\.[js, css]+/g, /webpackManifest\.[0-9a-z]+\.js/g, /.DS_Store\.[0-9a-z]+/g],
importScripts: ['offline/offline.1a2b3c4df1.js'],
dontCacheBustUrlsMatching: /./,
minify: false,
skipWaiting: false,
runtimeCaching: [ {
urlPattern: /_nch\.[0-9a-z]+\.[js, css]+/g,
handler: 'fastest',
options: {
cache: {
name: 'jd-internal-script',
maxEntries: 10,
},
},
}, {
urlPattern: /webpackManifest\.[0-9a-z]+\.js/g,
handler: 'networkFirst',
options: {
cache: {
name: 'jd-root-doc',
},
},
}],
}),