最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CachingOptimising Fonts with Service Worker - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 5, 2019 at 8:36 Niklas asked Mar 29, 2018 at 9:50 NiklasNiklas 1,30919 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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./s/opensans/v15/memnYaGs126MiZpBA-UFUKWyV9hvIqOxjaPXZSk.woff2);
  src: url(https://fonts.gstatic./s/opensans/v15/memnYaGs126MiZpBA-UFUKWyV9hnIqOxjaPXZSk.woff2);
}
...

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

self.addEventListener('fetch', event => {
  if (/fonts.(googleapis|gstatic)./.test(event.request.url)) {
    // process caching font files
  }
})
发布评论

评论列表(0)

  1. 暂无评论