user1256378
user1256378

Reputation: 742

workbox cache offline wordpress site

newbie with workbox and I'm trying to cache the front page of a wordpress site [Or all the pages] to comply with lighthouse PWA Failed Audit:

Does not respond with a 200 when offline If you're building a Progressive Web App, consider using a service worker so that your app can work offline. Learn more.

I've made function:

    /**
 * 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' );

And the corresponding sw.js file is:

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]}
    })
);

The serviceWorker is registered correctly but the cache does not work as intended.

Any suggestions? Or any more information needed?

Upvotes: 2

Views: 1296

Answers (1)

davidchannal
davidchannal

Reputation: 128

Try adding a new route, for example, if you are using wordpress:

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

This will cache the wordpress html page

ps: change the cacheName to yours

Upvotes: 2

Related Questions