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) {
if(!element.getAttribute(‘loading’)){
element.before(before);
element.setAttribute(‘loading’, ‘lazy’);
element.after(after);
}
}
}

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

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

addEventListener(‘fetch’, event => {
event.respondWith(handleRequest(event.request))
})

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

2 Likes

Thanks, it’s working properly now.