Dynamic Cache/Cache on Demand in Service workers

Posted on 5th April | Author - Neha Sharma
service workers-dynamice Cache

Service workers is the well know term now in web developers. All credits goes to the progressive web apps for the popularity of Service workers.

It won’t be wrong to say service workers are the backbone of the PWA. Most of the impressive features of PWA or the features which made PWA popular in industry in just a short span of time are dependent on the service workers only. Few of the features are:

  • Cache
  • Background sync
  • Push Notifications
  • Offline Content

In this article, we will be learning about On-Demand Dynamic Caching with service workers.

Did you checked our last blog on Redux? Redux for Dummies.

What is Dynamic Cache/Cache on Demand

It is hard to make all files cached static in the service workers. Your file will end up look like something like this. Also, there could be the possibility that the user might not be visiting each and every page of your app then why to pollute their cache by installing so many files and slow down the phone. Wouldn’t be nice that we keep caching the pages as per the user visit the pages? And this is known as the Dynamic cache or cache on demand.

Why it is important:

  • Clean Code - Your code don’t end up looking like your caching your whole application with 50+ pages
  • Clean Cache - Your cache will have only those pages which the users visited. Hence you are not polluting the user’s cache and only caching what the user demanded.

Here is the code:

  • The moment user request a page , the fetch will intercept the request
  • Fetch will return a promise .
  • We ll open the dynamiccaches and put the -
  • We ll put the request into the caches - caches.put with the response clone returned from the fetch promise
  • Return the response
  • If promise got rejected fetch will go to caches (pre-cache) to match the request URL request

In our current example we have below files are pre-cached:

The files which we are getting pre-cache

We have benefit.html which is not pre-cache We want to get benefit.html to be cached on-demand.

Do check Video of same on Our channel : JSLovers

Now, go to to the browser and try to access the app. Everything will be working good. Go to the application and check both cache

Service workers
Cache - pre-cache
Service workers
Cache - dynamic-cache

Now, go offline, access the home page it must be working fine. As we have the index.html in cache. Now, access benefit.html and you must be seeing broken page.

Service workers
Broken page while accessing the benefit.html

Now, connect back go to application and check the dynamic caches.

Service workers
Updated Dynamic Cache

Go offline again and try to re-access the benefit.html it must be working perfectly.

Service workers

Want to know more about me? Follow me at : Twitter, Linkedin, Medium