Skip to content

Instantly share code, notes, and snippets.

@alfari16
Created January 18, 2025 01:41
Show Gist options
  • Save alfari16/ca07152e9dd918906c68e895636bafda to your computer and use it in GitHub Desktop.
Save alfari16/ca07152e9dd918906c68e895636bafda to your computer and use it in GitHub Desktop.
cloudflare worker early hints implementation
export default {
async fetch(request, env) {
switch (request.method) {
case 'HEAD':
case 'GET':
const url = new URL(request.url);
const key = decodeURIComponent(url.pathname);
// replace suffix / after concating cause raw key still needed for regex
let objKey = key.replace(/\/+$/gm, '');
// regex to detect path that doesnt has extension
if (!/[^\/]+\.[^\/.]+$/.test(key)) {
objKey += '/index.html';
}
// MY_BUCKET is r2 binding
let object = await env.MY_BUCKET.get(objKey, opts);
if (object === null)
return new Response(`404 Not Found`, { status: 404 });
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('etag', object.httpEtag);
headers.set('Content-Encoding', 'gzip');
if (objKey.endsWith('.html')) {
const text = await object.text();
const links = extractEarlyHintsAssets(host, text);
for (const l of links) {
let v = `<${l.url}>; rel=${l.isPreload ? 'preload' : 'preconnect'}`;
if (l.isPreload) v = `${v} as=${l.as}`;
headers.append('link', v);
}
return new Response(text, {
headers,
});
}
return new Response(object.body, {
headers,
});
default:
return new Response('Method Not Allowed', {
status: 405,
headers: {
Allow: 'GET, HEAD',
},
});
}
},
};
const extractEarlyHintsAssets = (host, body) => {
const reg = new RegExp(`^(?:/|https?://${host.replaceAll('.', '.')}).*$`);
const s = new Set();
return [
...body.matchAll(
/<link.+href="([^"]+)".*>|<script.+src="([^"]+)".*>|<img.+src="([^"]+)".*>/gm,
),
]
.flatMap((match) => match.slice(1))
.map((url) => {
if (!url) return { url: '' };
url = url.split('?')[0];
let as = '';
if (url.endsWith('.css')) as = 'style';
else if (url.endsWith('.js')) as = 'script';
const isPreload = as != '' && reg.test(url);
if (!isPreload) {
try {
const u = new URL(url);
url = `${u.protocol}//${u.host}`;
} catch (err) {
url = '';
}
} else {
url = url.replace(`https://${host}`, '');
}
return { isPreload, url, as };
})
.filter((link) => {
let found = true;
if (s.has(link.url)) found = false;
else s.add(link.url);
return link.url && link.url !== `https://${host}` && found;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment