简体   繁体   中英

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.

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); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM