Arup Rakshit
Arup Rakshit

Reputation: 118261

NetworkFirst cache strategy not saving the html content of an url

I am first time using serviceworker using workbox, have no prior experience. I want when a user visits a url, the corresponding html must be saved to cache, so when the app is offline, the content of the url serves from the cache. But I don't see the content in the cache from browser devtool. What am I missing here?

import { registerRoute } from "workbox-routing";
import { precacheAndRoute } from "workbox-precaching";
import {skipWaiting} from 'workbox-core';
import {NetworkFirst, CacheFirst} from 'workbox-strategies';

// ...

function jsonResponse(value) {
  return new Response(JSON.stringify(value), {
    headers: { "Content-Type": "application/json" },
    status: 202,
  });
}

console.log("Workbox is loaded");

skipWaiting();


/* injection point for manifest files.  */
precacheAndRoute(self.__WB_MANIFEST);

const pagesCache = new NetworkFirst({
  cacheName: 'pages-cache',
});

registerRoute(
  new RegExp("/projects/[-a-z0-9]+/edit$"),
  args => {
    console.log('Got in here..');
    return pagesCache.handle(args);
  }
);

so when I go to offline I see.

pwa

Upvotes: 1

Views: 569

Answers (1)

pate
pate

Reputation: 5253

Your code is mixing both precaching and runtime caching parts from the Workbox library. Some parts of it might work, some not.

By saying "I want when a user visits a url, the corresponding html must be saved to cache, so when the app is offline, the content of the url serves from the cache." it seems that you want what is called a network first caching strategy. The simplest configuration for that using Workbox would be:

import {registerRoute} from 'workbox-routing';
import {NetworkFirst} from 'workbox-strategies';

registerRoute(
  new RegExp('/'),
  new NetworkFirst()
);

More info about the strategy here: https://developers.google.com/web/tools/workbox/modules/workbox-strategies#network_first_network_falling_back_to_cache

I also suggest you to read a primer on Service Workers themselves. You may find one eg. here https://developers.google.com/web/fundamentals/primers/service-workers/

Upvotes: 1

Related Questions