簡體   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