speedcf-libs
v1.0.0
Published
> collection of optimization done in Cloudflare Workers
Downloads
2
Readme
Cloudflare Speed's libraries
collection of optimization done in Cloudflare Workers
Demo
Edge side includes, Google font optimizations, h2 default priorities, 3rd party rewrite and serve stale-while-revalidate in a worker:
// overrides URL constructor:
// to encode % so Worker's URL parser won't throw
import "@cloudflare/patch-workers-url";
import { EdgeSideIncludesOptimization } from "@cloudflare/edge-side-includes";
import { GoogleFontOptimization } from "@cloudflare/google-fast-fonts";
import { Rewrite3rdPartyOptimization } from "@cloudflare/rewrite-3rd-party";
import { h2DefaultPrioritiesOptimization } from "@cloudflare/h2-default-priorities";
import { StaleWhileRevalidateOptimization } from "@cloudflare/stale-while-revalidate";
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
const request = event.request;
const esi = new EdgeSideIncludesOptimization(request);
const fonts = new GoogleFontOptimization(request);
const thirdParty = new Rewrite3rdPartyOptimization(request);
const h2Prio = new h2DefaultPrioritiesOptimization(request);
const swr = new StaleWhileRevalidateOptimization(request);
if (fonts.isGoogleFontRequest()) {
return fonts.serveGoogleFont();
}
if (thirdParty.isProxiedScriptRequest()) {
return thirdParty.proxyScriptRequest();
}
let res = await swr.fetchWithCache(event);
res = h2Prio.withPriority(res);
return transform(request, { thirdParty, esi, fonts }, res);
}
function transform(request, { thirdParty, esi, fonts }, response) {
const rewriter = thirdParty.withThirdPartyTransform(
fonts.withGoogleFontsTransform(
response,
esi.withESITransform(new HTMLRewriter())
)
);
return rewriter.transform(response);
}
Contributing
Install
yarn
yarn bootstrap
Run tests
yarn test