Skip to content

Instantly share code, notes, and snippets.

@ramannanda
Last active January 13, 2024 19:35
Show Gist options
  • Save ramannanda/6874691fb284c44de28d2807fda9c7b8 to your computer and use it in GitHub Desktop.
Save ramannanda/6874691fb284c44de28d2807fda9c7b8 to your computer and use it in GitHub Desktop.
Service Worker for Google Fonts - Rewrite Font-Display
/*
* Rewrite Response from Google Fonts to include 'font-display: swap'
* Based from: https://css-tricks.com/google-fonts-and-font-display/
*/
// Maintain Cache Versions
const CURRENT_CACHES = {
font: "google-font-cache-v3"
};
self.addEventListener("fetch", event => {
event.respondWith(handleRequest(event));
});
async function handleRequest(event) {
// Break out if request does not match
if ((event.request.cache === 'only-if-cached' &&
event.request.mode !== 'same-origin') ||
event.request.url.indexOf("https://fonts.googleapis.com/css") !== 0) {
return await fetch(event.request);
}
const request = new Request(
// Rewrite Request Object
event.request.url, {
method: event.request.method,
body: event.request.body,
mode: 'cors',
credentials: 'omit',
cache: event.request.cache,
redirect: event.request.redirect,
referrer: event.request.referrer,
integrity: event.request.integrity
}
);
const response = await fetch(request);
if (response.status < 400) {
const cache = await caches.open(CURRENT_CACHES.font);
const cacheResponse = await cache.match(event.request);
if (cacheResponse) {
return cacheResponse;
}
const css = await response.text();
// Patch CSS to Include "font-display: swap"
const patched = css.replace(/}/g, " font-display: swap; \n}");
const newResponse = new Response(patched, {headers: response.headers});
cache.put(event.request, newResponse.clone());
return newResponse;
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment