Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show progress while caching files using a service worker

I'm not too familiar with JavaScript and have a hard time getting into service workers.

I want to make a whole webapp available offline using service workers to cache the necessary files at page load. Though this is working, it takes quite some time until all the files are downloaded to disk, which makes the browser unresponsive and the user impatient.

I wonder, what is the best way to show progress while the service worker is doing its magic? In the way of "Downloading file 25 of 100".

How can the client know the progress of the service worker? Since the worker has no DOM access. Do I have to use messages between the worker and the client?

This is my first question here and I hope I made myself clear, do not post a duplicate (didn't find anything) and obeyed all the rules.

Thanks in advance for any help or guidance.

like image 366
Kaarug Avatar asked Mar 27 '18 21:03

Kaarug


1 Answers

The example below emits progress indicator events from a Service Worker. You can keep a running progress total for multiple PWA requests reworking the code a bit and changing const total (declared here) to let total in global scope to calculate a running byte count total of all the responses. Use HTTP2, otherwise the "total" size will grow as new responses start to come in, yielding inaccurate progress bars. HTTP2 will most likely start all responses at the same time, allowing you to calculate the grand total from the onset, which provides better UX accuracy.

https://fetch-progress.anthum.com/sw-basic/

ReadableStream is required and not fully implemented by browsers. Mind the browser support.

like image 137
AnthumChris Avatar answered Oct 18 '22 04:10

AnthumChris