本文介绍了使用 ReadableStream 和 Response 从 Service Worker 的 fetch 事件返回 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Service Worker 中返回 HTML 响应的流,但浏览器似乎无法解析它(我在此测试中使用 chrome).

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).

所以,这个有效(在 fetch 事件中):

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

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

但是当我使用 ReadableStream 时,它不再在浏览器中呈现:

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.

我使用过的资源:

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

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

更新

我的问题与此类似,但针对异步情况.

推荐答案

由于某些原因,当您不使用 ReadableStream.getReader

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

此外,当您将 ReadableStream 传递给 Response ctorResponse.text 方法不处理流,而是返回对象的 toString().

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

这篇关于使用 ReadableStream 和 Response 从 Service Worker 的 fetch 事件返回 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 07:54