I'm trying to use HTMLRewriter to inject a preload <link> into web pages on my site, but nothing is happening.
The code I am using is:
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
class ElementHandler {
element(element) {
element.append(`<link rel="preload" href="path/to/image.jpg" as="image">`, {html: true});
}
}
async function handleRequest(req) {
const res = await fetch(req)
return new HTMLRewriter().on("head", new ElementHandler()).transform(res)
}
I spoke to somebody from Cloudflare and they couldn't see anything wrong with it, but it's still not working. The <link> isn't there.