Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching/Optimising Fonts with Service Worker

I have a basic Service worker script that caches my fonts.css file. The service worker are getting registered on page load in my index.html file but I am also loading the fonts.css file directly in my index.html.

Is it right that the service worker file will intercept the request and responds with the cached fonts.css file? Or does caching the fonts.css file has no effect as the Browser still has to request the listed fonts?

I believe the latter is whats going on but it would be great if someone could clear thing up for me. Would be the best approach to cache the whole fonts folder not only the fonts.css file?

like image 415
Niklas Avatar asked Mar 06 '23 13:03

Niklas


1 Answers

The Service Worker will need to cache the CSS file and the associated font files (.woff2, .ttf, etc) specified within that CSS file that the browser loads.

For example, when using Google Fonts Open Sans CSS file, various URLs list the font files (URLs differ based on the browser you're using and font types supported).

...

@font-face {
  src: url(https://fonts.gstatic.com/s/opensans/v15/memnYaGs126MiZpBA-UFUKWyV9hvIqOxjaPXZSk.woff2);
  src: url(https://fonts.gstatic.com/s/opensans/v15/memnYaGs126MiZpBA-UFUKWyV9hnIqOxjaPXZSk.woff2);
}
...

In this example, your Service Worker could cache all files that match domains "fonts.googleapis.com" and "fonts.gstatic.com"

self.addEventListener('fetch', event => {
  if (/fonts.(googleapis|gstatic).com/.test(event.request.url)) {
    // process caching font files
  }
})
like image 188
AnthumChris Avatar answered Mar 16 '23 13:03

AnthumChris