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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With