Refactor with TransformStream as described by @ricea:
The examples would be cleaner with TransformStream, but unfortunately no browser is shipping it yet. You could be really concise, something like (totally untested)
fetchEvent.respondWith(new Response(response.body.pipeThrough(new TransformStream({
transform(chunk, controller) {
loaded += chunk.length;
progress({loaded, total});
controller.enqueue(chunk);
}
})), response));
Refactor with
TransformStreamas described by @ricea: