簡體   English   中英

服務工作者為多語言站點獲取靜態資產

[英]Service worker fetching static assets for multilingual site

我有一個多語言結構的靜態網站(用 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.htmles/offline.html被離線訪問並加載 CSS 和 JS 文件時。 問題是,由於 es/index.html 文件將 CSS 和 JS 引用為../static/css/styles.css../static/js/main.js ,因此他們無法在緩存中找到這些文件. 我試圖找到一種方法來改變請求和響應,但到目前為止我失敗了。 有什么幫助嗎?

好吧,您可以在代碼中編寫一些邏輯,其中caches.match(event.request)更改為類似caches.match(event.request) || caches.match(*canonical-url*) caches.match(event.request) || caches.match(*canonical-url*) (偽代碼)。 如果您已經嘗試過,您的代碼中可能存在錯誤。 另一種選擇是緩存文件兩次 - 使用它們的根相對路徑和它們的規范“../”路徑。 這當然不是最佳的,因為緩存被使用了兩次。

我認為最好的選擇是生成您的站點,以便它始終使用相對於根目錄的靜態資產路徑。 用“/static/bla”替換所有“../static/bla”,一切都應該非常整齊地開箱即用:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM