Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ReadableStream with Response to return HTML from fetch event of Service Worker

I'm trying to return a stream for the HTML response in a service worker but the browser does not seem to be able to parse it (I'm using chrome for this test).

So, this one works (in the fetch event):

event.respondWith(new Response("<h1>Yellow!</h1>", { headers: { "Content-Type": "text/html" }}))

But when I use a ReadableStream it no longer renders in the browser:

const stream = new ReadableStream({
    start(controller) {
        controller.enqueue("<h1>Yellow!</h1>")
        controller.close()
    }
})
event.respondWith(new Response(stream, { headers: { "Content-Type": "text/html" }}))

It seems like maybe the browser doesn't understand that I'm sending it a stream. But I don't know what headers I would need to use so the above works.

Resources that I have used:

https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples

https://philipwalton.com/articles/smaller-html-payloads-with-service-workers/

UPDATE

My question similar to this one but for asynchronous case.

like image 813
Jon49 Avatar asked Oct 12 '25 20:10

Jon49


1 Answers

For some reason it doesn't work when you don't lock stream with ReadableStream.getReader

Also when you pass ReadableStream to Response ctor, the Response.text method doesn't process the stream and it returns toString() of an object instead.

const createStream = () => new ReadableStream({
  start(controller) {
    controller.enqueue("<h1 style=\"background: yellow;\">Yellow!</h1>")
    controller.close()
  }
})

const firstStream = createStream().getReader();
const secondStream = createStream().getReader();

new Response(firstStream, {
      headers: {
        "Content-Type": "text/html"
      }
    })
  .text()
  .then(text => {
    console.log(text);
  });
    

secondStream.read()
  .then(({
    value
  }) => {

    return new Response(value, {
      headers: {
        "Content-Type": "text/html"
      }
    });

  })
  .then(response => response.text())
  .then(text => {
    console.log(text);
  });
like image 51
Józef Podlecki Avatar answered Oct 14 '25 08:10

Józef Podlecki