Created
November 8, 2021 20:21
-
-
Save pmeenan/40a0a63d505ee8aec429dfe73f8a0723 to your computer and use it in GitHub Desktop.
Adding Priority Hints with Cloudflare Workers
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(handleRequest(event.request)) | |
}); | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
const host = request.headers.get('x-host'); | |
if(!host) { | |
return new Response('x-host header missing', {status: 403}); | |
} | |
url.hostname = host; | |
const bypassTransform = request.headers.get('x-bypass-transform'); | |
const acceptHeader = request.headers.get('accept'); | |
if((acceptHeader && acceptHeader.indexOf('text/html') >= 0) && | |
(!bypassTransform || (bypassTransform && bypassTransform.indexOf('true') === -1))) { | |
const response = await fetch(url.toString(), request); | |
return new HTMLRewriter() | |
.on('div.has-hero>div.content>article.story-1>div.m>a>picture>img', new prioritizeHigh() /* Fox News */) | |
.on('img.pica-circus', new prioritizeHigh() /* Ling's Cars */) | |
.on('img#FMP-target', new prioritizeHigh() /* Airbnb */ ) | |
.on('img.mainImageMobile[alt="1"]', new prioritizeHigh() /* Amazon PDP */ ) | |
.on('img[data-carousel-first-image]', new prioritizeHigh() /* etsy */ ) | |
.on('img.primary-image', new prioritizeHigh() /* BestBuy */ ) | |
.on('img[elementtiming="TTVR.Infopane"]', new prioritizeHigh() /* MSN */) | |
.on('img[src$="learn_hero.jpg"]', new prioritizeHigh() /* developers.google.com */) | |
.on('img.rYD0Re', new prioritizeHigh() /* Google Flights */) | |
.on('img.dn', new prioritizeHigh() /* Cloudflare blog */) | |
.transform(response); | |
} | |
// Otherwise just proxy the request | |
return fetch(url.toString(), request) | |
} | |
class prioritizeHigh { | |
element(element) { | |
element.removeAttribute('loading'); | |
element.setAttribute('importance', 'high'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment