Created
June 5, 2019 00:12
-
-
Save skrater/66c9e42e620436cefb6936ccf862f42a to your computer and use it in GitHub Desktop.
Cloud flare worker lazy load js
This file contains 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(handle(event.request)); | |
}); | |
const urls = { | |
'certificate': 'https://static.eventials.com/evCertificate/assets/ev-certificates.$HASH.js' | |
} | |
const hashes = { | |
'certificate': '79fa861b49cdc1a2f7aa' | |
} | |
function makeURL(component) { | |
return urls[component].replace('$HASH', hashes[component]) | |
} | |
function makeScript(url) { | |
return `(function() { | |
var script = document.createElement('script'); | |
script.src = '$URL'; | |
document.head.appendChild(script); | |
})();`.replace('$URL', url) | |
} | |
function makeScriptAndURL(component) { | |
return makeScript(makeURL(component)) | |
} | |
async function handle(request) { | |
const queryString = new URL(request.url).searchParams.get('name') | |
var scripts = ['(function(){})();'] | |
if (queryString) { | |
const components = queryString.split(',') | |
components.forEach((name) => { | |
if (name in urls) { | |
scripts.push(makeScriptAndURL(name)) | |
} | |
}); | |
} | |
return new Response(scripts.join('')) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment