我正在尝试缓存wordpress站点的首页或所有页面,以遵守灯塔PWA失败审计:
如果您正在构建一个渐进Web应用程序,请考虑使用服务工作人员,以便您的应用程序可以脱机工作。了解更多信息。
我已经发挥了作用:
/**
* Callback that adds the service worker
*
*/
function brs_add_service_worker_callback() {
?>
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
navigator.serviceWorker.register('<?php echo plugin_dir_url( __FILE__ ).'js/sw.js?v'.get_plugin_data(__FILE__)['Version']?>');
});
}
</script>
<?php
}
add_action( 'wp_footer', 'brs_add_service_worker_callback' );相应的sw.js文件是:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.2.0/workbox-sw.js');
// Ignore preview and admin areas
workbox.routing.registerRoute(/wp-admin(.*)|(.*)preview=true(.*)/,
workbox.strategies.networkOnly()
);
// Stale while revalidate for JS and CSS that are not precache
workbox.routing.registerRoute(
/\.(?:js|css)$/,
workbox.strategies.staleWhileRevalidate(),
);
// We want no more than 50 images in the cache. We check using a cache first strategy
workbox.routing.registerRoute(/\.(?:png|gif|jpg|webp)$/,
workbox.strategies.cacheFirst({
cacheName: 'images-cache',
cacheExpiration: {
maxEntries: 50
}
})
);
// We need cache fonts if any
workbox.routing.registerRoute(/(.*)\.(?:woff|eot|woff2|ttf|svg)$/,
workbox.strategies.cacheFirst({
cacheExpiration: {
maxEntries: 20
},
cacheableResponse: {
statuses: [0, 200]
}
})
);
workbox.routing.registerRoute(/https:\/\/fonts.googleapis.com\/(.*)/,
workbox.strategies.cacheFirst({
cacheExpiration: {
maxEntries: 20
},
cacheableResponse: {statuses: [0, 200]}
})
);serviceWorker已正确注册,但缓存不按预期工作。
有什么建议吗?或者需要更多的信息?
发布于 2018-08-14 09:02:24
尝试添加一个新的路由,例如,如果您正在使用wordpress:
workbox.routing.registerRoute(new RegExp('/(.*)/'),
workbox.strategies.cacheFirst({
cacheName,
plugins: [
new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
}),
],
}));这将缓存wordpress html页面。
ps:将cacheName改为您的
https://stackoverflow.com/questions/50517412
复制相似问题