Keep track of progress while precaching assets with the Workbox

泪湿孤枕 提交于 2021-01-28 03:12:39

问题


Imagine we have N assets that need to be pre-cached with a service-worker once user navigated to the web site. We have appropriate precache-manifest.js with listed N-files and we are using workbox.precaching.precacheAndRoute([...]) to configure needed behavior (default CRA setup)

Is there a way to keep track of precaching progress when using workbox.precaching.precacheAndRoute or workbox.precaching.precache?

I imagine it could be something like passing a parameter-callback function to the workbox.precaching.precacheAndRoute along with the array of entries to precache. And this callback is invoked for each cached entry..

Is there any solution or workaround for this issue? Thanks!


回答1:


There is no event or callback provided by workbox to notify if precaching is completed. But here is a workaround i've managed to come up with using postMessage to notify the client that precaching is completed.

// sw-precache.js
workbox.precaching.precacheAndRoute(self.__precacheManifest)

const interval = setInterval(() => {
    caches.open(workbox.core.cacheNames.precache).then(cache => {
        cache.keys().then(keys => {
            if (keys.length >= self.__precacheManifest.length) {
                clearInterval(interval)
                self.clients.matchAll().then(clients => {
                    clients.forEach(client => client.postMessage('afterPrecache'))
                })
            }
        })
    })
}, 1000)

And in your client,

// index.html
....
navigator.serviceWorker.onmessage = (e) => {
    if (e.data === 'afterPrecache') {
        // precaching completed
    }
}
....

You can even tweak the above solution to get track of precaching progress.




回答2:


In theory it should be possible to add your own custom plugin to the precaching component using addPlugins

I hope to have a play with proving this theory at some point soon using cacheDidUpdate event, I am not certain that I can communicate the progress easily back to the page though. The doubt in my mind is whether I can reliably listen to any messages in the page that is registering, but not yet controlled by the precaching serviceworker



来源:https://stackoverflow.com/questions/55199298/keep-track-of-progress-while-precaching-assets-with-the-workbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!