如何从脱机页面的缓存中加载图像



所以我正在尝试弄清楚如何在我的Rails应用程序中为我的离线.html页面加载缓存图像。我有两个问题:

  1. 我不确定究竟在哪里保存图像。
  2. 我不确定如何正确加载图像的源img src="???"

我的serviceworker.js.erb当前正在正确缓存图像:

function onInstall(event) {
  event.waitUntil(
    caches.open(CACHE_NAME).then(function prefill(cache) {
      return cache.addAll([
        '<%= asset_path "base.js" %>',
        '<%= asset_path "minimal.css" %>',
        '/offline.html',
        '<%= asset_path "cute-cat.png" %>',
        '<%= asset_path "cute-dog.png" %>',
      ]).then(function () {
        console.log("WORKER: Install completed");
      });
    })
  );
}
function onFetch(event) {
  if ( requestBlackListed(event.request) ) { return; }
  event.respondWith(
    caches.match(event.request).then(function (cached) {
      if (cached && shouldReturnStraightFromCache(event.request.url)) {
        return cached;
      }
      return fetch(event.request)
        .then(fetchedFromNetwork)
        .catch(function fallback() {
           return cached || caches.match("/offline.html");
         })
      }
    )
  );

我的offline.html看起来很像这样:

<!DOCTYPE html>
<html>
<head>
  <title>You are not connected to the Internet</title>
  <meta property="og:url" content="offline.html" />
  <meta property="og:title" content="Looks like you've lost your Internet connection" />
</head>
<body>
  <!-- This file lives in public/offline.html -->
  <div class="container">
    <div>
      <a href="/"><img src="/app/assets/images/cute-cat.png"/></a>
      <img src="/app/assets/images/cute-dog.png" />
      <p>You're offline!.</p>
    </div>
  </div>
</body>
</html>

图像当前正在从/app/assets/images/加载,但它不起作用。我认为更明智的解决方案是从缓存而不是资产文件夹中加载两个图像。任何想法都会很棒。

编辑:添加了获取处理程序(onFetch函数(。

对,您加载图像就像页面在线一样。

  1. 我不确定将图像保存在哪里。 - 让软件处理它。 只需在软件中正确声明路径,就像在线加载它们一样。 它应该相对于您的软件所在的位置。
  2. 我不确定如何正确加载图像的源 img src="???"。- 将您的离线页面视为在线页面。 SW 将查找资产是否已缓存。

最新更新