Created
October 11, 2019 02:24
-
-
Save theKashey/c8ec3c6dc7dc4de60bf94668057f65f2 to your computer and use it in GitHub Desktop.
cloudflare HTTP(not HTML!) prefetch
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
// see cloudflare workers - https://workers.cloudflare.com | |
addEventListener('fetch', event => { | |
event.respondWith(fetchAndStream(event.request)) | |
}) | |
async function fetchAndStream(request) { | |
let streamResponse = fetch(request); // dont await, as majority of CF examples do | |
let { readable, writable } = new TransformStream() | |
// once lambda would answer - we would pipe the result | |
streamResponse.then(response => { | |
// yep, you are going to loose all these headers :( | |
console.log('lost headers', [...response.headers.keys()]); | |
response.body.pipeTo(writable) | |
}); | |
// kick off the first piece of data to "flush" the headers | |
// haven't found a better way :( | |
const writer = writable.getWriter(); | |
const encoder = new TextEncoder() | |
writer.write(encoder.encode('<!-- -->')); // adds <!-- --> before HTML | |
writer.releaseLock(); | |
const fonts = [ | |
array of your fonts. They are usually static | |
]; | |
const scripts = [ | |
array of your scripts. And that's not so easy (deploy worker from CI) | |
] | |
// pipe the response, once it would be ready... | |
return new Response(readable, { | |
status: 200, | |
headers: [ | |
// well, you have to hardcode all headers. | |
['Content-Type','text/html; charset=utf-8'], | |
['x-powered-by', 'cloud-prefetcher '], | |
...fonts.map(prefetchFont), | |
...scripts.map(prefetchScript), | |
] | |
}) | |
} | |
function prefetchFont(font) { | |
return ['Link', `<${font}>; rel=preload; as=font; crossorigin; type="font/woff2"`] | |
} | |
function prefetchScript(script) { | |
return ['Link', `<${script}>; rel=preload; as=script; type="application/javascript"`], | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment