Reply
Highlighted
Member
Posts: 1
Registered: ‎01-27-2020

Caching Fetch API response to prevent unnecessary multiple calls

So I'm using Fetch API for my mobile PWA, which is basically just written in HTML and JQuery/JS.

Basically if you click on a tab for the first time, I want it to load the response HTML (easy).

However, if you click away and click back to it, I don't want it to reload the response HTML just yet.

I want it to simply display the response HTML from the first instance of loading.

Fetch API doesn't allow me to tweak how long I can cache the response; the best is only 'force-cache' which is a forever cache, which is not what I want. So I'm thinking of "hacking" it to simulate a fake cache, meaning just place the response HTML into a div using the JQuery on first loading, setTimeout() for 15 minutes or whatever (after which it empties the div), and each time the link is clicked, I check within the div first to see if it's populated. If yes, just show the div itself. If no, reload the link using Fetch.