我建议将它用作更大workbox-sw
框架的一部分,作为插件。这是示例代码的一个版本,经过修改以用于importScripts()
从 CDN 中提取 Workbox 代码。或者,您可以使用 ES2015 模块语法,然后使用 Rollup 或 Webpack 之类的捆绑器,将本地的相关代码包含node_modules
到最终的 service worker 文件中,而不是使用 CDN 上的预打包包。
importScripts('https://unpkg.com/workbox-runtime-caching@1.3.0');
importScripts('https://unpkg.com/workbox-routing@1.3.0');
importScripts('https://unpkg.com/workbox-background-sync@1.3.0');
let bgQueue = new workbox.backgroundSync.QueuePlugin({
callbacks: {
replayDidSucceed: async(hash, res) => {
self.registration.showNotification('Background sync demo', {
body: 'Product has been purchased.',
icon: '/images/shop-icon-384.png',
});
},
replayDidFail: (hash) => {},
requestWillEnqueue: (reqData) => {},
requestWillDequeue: (reqData) => {},
},
});
const requestWrapper = new workbox.runtimeCaching.RequestWrapper({
plugins: [bgQueue],
});
const route = new workbox.routing.RegExpRoute({
regExp: new RegExp('^https://jsonplaceholder.typicode.com'),
handler: new workbox.runtimeCaching.NetworkOnly({requestWrapper}),
});
const router = new workbox.routing.Router();
router.registerRoute({route});