工作箱缓存离线wordpress站点

时间:2018-05-24 20:11:05

标签: wordpress service-worker workbox

newbox with workbox,我试图缓存wordpress网站的首页[或所有网页]以符合灯塔PWA失败的审核:

离线时不响应200 如果您正在构建渐进式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已正确注册,但缓存无法按预期工作。

有什么建议吗?还是需要更多信息?

1 个答案:

答案 0 :(得分:1)

例如,如果您使用的是wordpress,请尝试添加新路由:

workbox.routing.registerRoute(new RegExp('/(.*)/'), 
workbox.strategies.cacheFirst({
    cacheName,
    plugins: [
      new workbox.cacheableResponse.Plugin({
        statuses: [0, 200],
      }),
    ],
}));

这将缓存wordpress html页面

ps:将cacheName更改为您的