我刚开始制作 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,
})
],
})
);
问题的屏幕截图(可以看出,图像缓存已正确填充,但我似乎无法在离线时显示它们)
任何有关如何解决此问题的帮助将不胜感激。