Workers - html rewriter - .before and .after

Hi, we’re trying to write a simple worker to insert load=“lazy” into image tags, which works fine with this script, and also to insert a tag before and close it after those image tags too - which isn’t working so well.

For some reason, the before and after elements are being wrapped in quotes on the page, so they just get printed as text. If anyone can help I’d be grateful. This script we’re using is:

const before = ‘’
const after = ‘’

class ElementHandler {
element(element) {
element.setAttribute(‘loading’, ‘lazy’);

async function handleRequest(req) {
const res = await fetch(req);

return new HTMLRewriter().on(‘img’, new ElementHandler()).transform(res)

addEventListener(‘fetch’, event => {

You will need to call before and after with ContentOptions where html is set to true.


Thanks, it’s working properly now.