Update cached dynamic views with Service Worker

  caching, javascript, php, service-worker, wordpress

I have implemented a Service Worker on my wordpress website, the cache seems to work correctly but I have a problem with the Cache Dynamico, it seems that it is saving the php view so when this view changes I keep seeing the previous one, for example, if I enter The cart page is being cached so if I add a product to the cart it continues to show the version of the cart without the product, how can I exclude the dynamic views from the cache?

This is my Service Worker

importScripts( 'assets/js/sw-utils.js' );

const STATIC_CACHE = 'static-v1';
const DYNAMIC_CACHE = 'dynamic-v1';
const INMUTABLE_CACHE = 'inmutable-v1';

const APP_SHELL = [
    '/',
    'assets/style.css',
];

const APP_SHELL_INMUTABLE = [
    'assets/boostrap.min.css',
];

self.addEventListener( 'install', e => {
    const cacheStatic = caches.open( STATIC_CACHE ).then(cache => cache.addAll( APP_SHELL ));
    const cacheInmutable = caches.open( INMUTABLE_CACHE ).then(cache => cache.addAll( APP_SHELL_INMUTABLE ));
    e.waitUntil( Promise.all([ cacheStatic, cacheInmutable ]) );
});

self.addEventListener( 'activate', e => {
    const respond = caches.keys().then( keys => {
        keys.forEach( key => {
            if ( key !== STATIC_CACHE && key.includes( 'static') ) {
                return caches.delete(key);
            }
        });
    });
    e.waitUntil( respond );
});

self.addEventListener( 'fetch', e => {
    const respond = caches.match( e.request ).then( res => {
        if ( res ) {
            return res;
        } else {
            return fetch( e.request ).then( newRes => {
                return updateDynamicCache( DYNAMIC_CACHE, e.request, newRes );
            });
        }
    });
    e.respondWith( respond );
});

This is what is in the sw-utils.js file

function updateDynamicCache( dynamicCache, req, res ) {
    if ( res.ok ) {
        return caches.open( dynamicCache ).then( cache => {
            cache.put( req, res.clone() );
            return res.clone();
        });
    } else {
        return res;
    }
}

This last function is the one that caches the files that are not in the immutable or static cache.

I appreciate your responses, Thank you.

Source: Ask PHP

LEAVE A COMMENT