我刚刚开始制作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);
然后检查日志以查看请求图像的时间,并查看该请求的流程。
如果您可以在网络面板失败时提供图像的信息或屏幕截图,也会很有帮助。