Created
January 4, 2021 00:27
-
-
Save mattbasta/89cd4a54952d1522dc91169acb639b62 to your computer and use it in GitHub Desktop.
Cloudflare worker to inline scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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