【问题标题】:How to load images from cache for the offline page?如何从缓存中为离线页面加载图像?
【发布时间】:2023-03-16 10:16:01
【问题描述】:

所以我想弄清楚如何在我的 Rails 应用程序中为我的 offline.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/ 加载,但它不起作用。我认为更聪明的解决方案是从缓存中加载这两个图像,而不是从资产文件夹中加载。任何想法都会很棒。

编辑:添加了 fetch 处理程序(onFetch 函数)。

【问题讨论】:

  • 向我们展示您的fetch 处理程序。您如何提供缓存的图像?你呢?

标签: html ruby-on-rails caching offline service-worker


【解决方案1】:

正确地,您加载您的图像,就好像页面在线一样。

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

【讨论】:

  • 嗯,有道理。我的问题是我无法使用 erb,我目前正在通过asset_path 缓存图像。通常我会为 img src 使用 erb,如下所示:&lt;img src=&lt;%= asset_path "cute_dog.png" %&gt;,但我不确定如何正确链接资产文件夹中的 src
  • 此响应不是实际的遮阳篷。
猜你喜欢
  • 2015-12-22
  • 2014-06-16
  • 2014-11-16
  • 2011-09-05
  • 1970-01-01
  • 2019-01-16
  • 2012-06-09
  • 2014-11-17
  • 1970-01-01
相关资源
最近更新 更多