繁体   English   中英

如何解决PWA中未显示来自缓存的图像的问题?

[英]How to fix an issue of images from cache not being displayed in my PWA?

我刚开始制作PWA。

我正在使用Workbox制作第一个PWA,这是一个非常基本的新闻获取应用程序。

我正在将newsapi.org用于新闻数据和工作 ,以使我的服务工作者成为可能。

我设法使除图像以外的所有内容脱机工作。

正确缓存图像的同时,激活脱机模式时不会显示图像

这是我的app.js文件:

const main = document.querySelector('main');
const sourceSelector = document.querySelector('#sourceSelector');
const defaultSource = 'the-washington-post';

window.addEventListener('load', e =>{
  updateNews();
  console.log('app file');
  updateSources();
  sourceSelector.value = defaultSource;

  sourceSelector.addEventListener('change', e=>{
    updateNews(e.target.value);
  })

  if('serviceWorker' in  navigator){
    try {
      navigator.serviceWorker.register('sw.js');
      console.log('SW Registered');
    } catch (e) {
        console.log('SW Registration failed');
    }

  }
});

async function updateSources(){


  const res = await fetch(`https://newsapi.org/v2/sources?apiKey=MyApiKey
`);
  const json = await res.json();
  sourceSelector.innerHTML = json.sources.map(src => `<option value =     "${src.id}">${src.name}</option>`).join('\n');
  console.log(json);
}

async function updateNews(source = defaultSource){
    const res= await fetch(`https://newsapi.org/v2/top-headlines?  sources=${source}&apiKey=MyApiKey`);
    const json = await res.json();
    main.innerHTML = json.articles.map(createArticle).join('\n');

};

function createArticle(article){
  return `
    <div class="article">
        <a href="${article.url}">
            <h2>${article.title}</h2>
            <img src="${article.urlToImage}">
              <p>${article.description}</p>
    </a>
  </div>
  `;


}

这是我的Service Worker文件(sw.js)

importScripts('https://storage.googleapis.com/workbox-  cdn/releases/3.0.0/workbox-sw.js');
const staticAssets = [
  './',
  './style.css',
  './app.js',
  './fallback.json',
];
workbox.precaching.precacheAndRoute(staticAssets
);

workbox.routing.registerRoute(
  new RegExp('.*\.js'),


  workbox.strategies.networkFirst({

  })
);
workbox.routing.registerRoute(
  new RegExp ('https://newsapi.org/'),

  workbox.strategies.networkFirst({

  })
);


workbox.routing.registerRoute(
  /.*\.(png|jpg|jpeg|svg|gif)/,
  workbox.strategies.staleWhileRevalidate({
    cacheName: 'news-images',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 50,
        maxAgeSeconds: 12 * 60 * 60,
      })
    ],
  })
);

问题的屏幕截图(可以看到,图像的缓存已正确填充,但离线时似乎无法显示它们)

在此处输入图片说明

任何有关如何解决此问题的帮助将不胜感激。

您可以通过将以下内容添加到服务工作者中来进一步调试它:

// Force development builds
workbox.setConfig({ debug: true });
// The most verbose - displays all logs.
workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);

然后检查日志以了解何时请求图像,并查看该请求的流程。

如果您可以在出现故障时在“网络”面板中提供信息或图像的屏幕截图,也将很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM