Javascript 服务人员正在为多语言站点获取静态资产

Javascript 服务人员正在为多语言站点获取静态资产,javascript,service-worker,Javascript,Service Worker,我有一个静态站点(由Pelican生成),具有多语言结构,例如 www.example.com/ www.example.com/index.html www.example.com/page1.html www.example.com/es/ www.example.com/es/index.html www.example.com/es/page1.html 我已使用service worker安装事件缓存了JS和CSS以及索引文件: const staticCacheName = 'st

我有一个静态站点(由Pelican生成),具有多语言结构,例如

www.example.com/
www.example.com/index.html
www.example.com/page1.html
www.example.com/es/
www.example.com/es/index.html
www.example.com/es/page1.html
我已使用service worker安装事件缓存了JS和CSS以及索引文件:

const staticCacheName = 'static-cache-v5';

const filesToCache = [
  '/',
  '/index.html',
  '/es/index.html',
  '/offline.html',
  'static/js/main..js',
  'static/css/styles.css',
]


self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(staticCacheName).then((cache) => {
      return cache.addAll(filesToCache);
    })
  );

  self.skipWaiting();
});
我正在使用缓存,回到网络策略:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});

我遇到的问题是,当离线访问
www.example.com/es/index.html
es/offline.html
并加载CSS和JS文件时。问题是,由于es/index.html文件引用CSS和JS作为
。/static/CSS/styles.CSS
。/static/JS/main.JS
,因此它们在缓存中找不到文件。我试图找到一种改变请求和响应的方法,但到目前为止我失败了。有什么帮助吗?

嗯,您可以在代码中编写一些逻辑,将
缓存.match(event.request)
更改为类似
缓存.match(event.request)|缓存.match(*规范url*)
(在伪代码中)。如果您已经尝试过,那么您的代码中可能有一个bug。另一种选择是缓存文件两次——使用其根相对路径和规范的“./”路径。这当然不是最优的,因为缓存被使用了两次

我认为最好的选择是生成您的站点,以便它始终使用根相对静态资产路径。将所有“./static/bla”替换为“/static/bla”,所有内容都应能很好地开箱即用:)