A Cloudflare Worker that uses HTMLRewriter in order to select assets from the page that we want to include in Link headers, so that Cloudflare can cache these and emit 103 Early Hints responses.
Curious about what each part of the code does and why it's used?
Check out my blog post!
If your site has a lot of img
/script
/link[rel=stylesheet]
elements, you will want to make sure you're scoping the selectors to the specific ones you want to preload! If your link
header gets too large, this can cause issues - many servers or CDNs limit the size of an individual header to 8192B (8KB).
Take a look at the Don't Overhint! section of the blog post.
- A Cloudflare Account and a website using Cloudflare.
- wrangler
103 Early Hints also supports rel=preconnect
hints - this will 'warm up' the connection ahead of requesting resources
and is good for assets that don't necessarily need preloading, but you will be fetching soon after the page load.
The recommendation is to do this for important third-party origins, i.e Google Analytics or Google Fonts
Preconnect Link headers to important third-party origins (e.g. an origin hosting the pages’ assets, or Google Fonts). https://blog.cloudflare.com/early-hints-performance/
In order to configure this, add an array of domains to the preconnect_domains
variable in wrangler.toml
.
[vars]
preconnect_domains = ["https://kian.org.uk", "https://www.google-analytics.com"]
- Make sure that Early Hints is enabled in Speed -> Optimization
- Clone the repository.
- Make sure that your
wrangler
logged in to your Cloudflare account. - Open
wrangler.toml
and add aroute
key as necessary to make the Worker run on your website.
route = { pattern = "example.com/*", zone_name = "example.com" }
- If necessary, make any changes to the HTML element selectors or add
rel=preconnect
hints as per preconnect domains. - Run
wrangler publish
and the Worker will be live on your website!