Created
May 20, 2019 21:18
-
-
Save notiv-nt/8c92f431fe2ed719f5104df1bc34f38c to your computer and use it in GitHub Desktop.
Service worker font-display polyfill
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
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