简体   繁体   English

使用 ReadableStream 和 Response 从 Service Worker 的 fetch 事件中返回 HTML

[英]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).我正在尝试为服务工作者中的HTML响应返回 stream,但浏览器似乎无法解析它(我正在使用 chrome 进行此测试)。

So, this one works (in the fetch event):所以,这个有效(在fetch事件中):

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:但是当我使用ReadableStream它不再呈现在浏览器中:

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.似乎浏览器不明白我正在向它发送 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://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#Examples

https://philipwalton.com/articles/smaller-html-payloads-with-service-workers/ 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由于某种原因,当您不使用ReadableStream.getReader锁定 stream 时,它不起作用

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.此外,当您将ReadableStream传递给Response ctor时, Response.text方法不会处理 stream 而是返回 object 的toString()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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