|
| 1 | +--- |
| 2 | +title: Transform HTML quickly with streaming content |
| 3 | +description: HTMLRewiter now supports streamed content for more efficient replacement of HTML elements |
| 4 | +products: |
| 5 | + - workers |
| 6 | +date: 2025-01-31T01:00:00Z |
| 7 | +--- |
| 8 | + |
| 9 | +import { Render, TypeScriptExample } from "~/components"; |
| 10 | + |
| 11 | +You can now transform HTML elements with streamed content using [`HTMLRewriter`](/workers/runtime-apis/html-rewriter). |
| 12 | + |
| 13 | +Methods like `replace`, `append`, and `prepend` now accept [`Response`](/workers/runtime-apis/response/) and [`ReadableStream`](/workers/runtime-apis/streams/readablestream/) |
| 14 | +values as [`Content`](/workers/runtime-apis/html-rewriter/#global-types). |
| 15 | + |
| 16 | +This can be helpful in a variety of situations. For instance, you may have a Worker in front of an origin, |
| 17 | +and want to replace an element with content from a different source. Prior to this change, you would have to load |
| 18 | +all of the content from the upstream URL and convert it into a string before replacing the element. This slowed |
| 19 | +down overall response times. |
| 20 | + |
| 21 | +Now, you can pass the `Response` object directly into the `replace` method, and HTMLRewriter will immediately |
| 22 | +start replacing the content as it is streamed in. This makes responses faster. |
| 23 | + |
| 24 | +<TypeScriptExample filename="index.ts"> |
| 25 | +```ts |
| 26 | +class ElementRewriter { |
| 27 | + async element(element: any) { |
| 28 | + // able to replace elements while streaming content |
| 29 | + // the fetched body is not buffered into memory as part |
| 30 | + // of the replace |
| 31 | + let res = await fetch('https://upstream-content-provider.example'); |
| 32 | + element.replace(res); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export default { |
| 37 | + async fetch(request, env, ctx): Promise<Response> { |
| 38 | + let response = await fetch('https://site-to-replace.com'); |
| 39 | + return new HTMLRewriter().on('[data-to-replace]', new ElementRewriter()).transform(response); |
| 40 | + }, |
| 41 | +} satisfies ExportedHandler<Env>; |
| 42 | +``` |
| 43 | +</TypeScriptExample> |
| 44 | + |
| 45 | +For more information, see the [`HTMLRewriter` documentation](/workers/runtime-apis/html-rewriter). |
0 commit comments