Skip to content

Instantly share code, notes, and snippets.

@mattbasta
Created January 4, 2021 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbasta/89cd4a54952d1522dc91169acb639b62 to your computer and use it in GitHub Desktop.
Save mattbasta/89cd4a54952d1522dc91169acb639b62 to your computer and use it in GitHub Desktop.
Cloudflare worker to inline scripts
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Respond to the request
* @param {Request} request
*/
async function handleRequest(request) {
const resp = await fetch(request);
const body = await resp.clone().text();
const remoteScripts = [];
body.replace(/src="(.*)"/g, (_, src) => {
remoteScripts.push(src);
});
const remoteScriptsSources = await Promise.all(
remoteScripts.map(async origSrc => {
let src = origSrc;
if (src.startsWith('//')) {
src = 'https:' + src;
}
return [origSrc, await (await fetch(src)).text()];
})
);
const scriptMap = remoteScriptsSources.reduce((acc, [src, body]) => {
acc[src] = body;
return acc;
}, {});
return new HTMLRewriter()
.on('script[src]', {
element(elem) {
const src = elem.getAttribute('src');
if (!(src in scriptMap)) {
console.warn(`${src} not in ${Object.keys(scriptMap)}`);
return;
}
elem.removeAttribute('src');
elem.removeAttribute('crossorigin');
elem.setAttribute('data-inlined-from', src);
elem.append(scriptMap[src], {html: true});
}
})
.transform(resp.clone());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment