Skip to content

Instantly share code, notes, and snippets.

@notiv-nt
Created May 20, 2019 21:18
Show Gist options
  • Save notiv-nt/8c92f431fe2ed719f5104df1bc34f38c to your computer and use it in GitHub Desktop.
Save notiv-nt/8c92f431fe2ed719f5104df1bc34f38c to your computer and use it in GitHub Desktop.
Service worker font-display polyfill
self.addEventListener('fetch', function(event) {
// Polyfill
if (/https:\/\/fonts.googleapis.com\/css/.test(event.request.url)) {
return event.respondWith(fontDisplayPolyfill(event.request));
}
return event;
});
async function fontDisplayPolyfill(request) {
const cache = await caches.open('font-v1');
const inCache = await cache.match(request);
if (inCache) {
return inCache;
}
const response = await fetch(request.url);
let css = await response.text();
if (css.search('font-display') === -1) {
css = css.replace(/}/g, 'font-display: swap; }');
}
const newResponse = new Response(css, {
headers: response.headers,
});
cache.put(request, newResponse.clone());
return newResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment