Search code examples
htmlcache-manifest

Can a manifest-managed resource fall back to its own cached copy when offline?


I'm using an HTML5 manifest to allow an application to work offline. I have a resource -- say /background.png -- that may update from time to time, but if the application is offline, the last-retrieved version is suitable for use. The behavior I want is for the browser to request /background.png normally if it's online, but to fall back to the cached version if the request fails because it's offline, the server is down, etc.

In my testing, having a manifest entry like

NETWORK:
/background.png

made the browser always try to request the resource. It would return an error, rather than returning a copy from the appcache, if it was offline. That's not what I want, but it is how NETWORK is supposed to behave as I understand it.

I also tried

FALLBACK:
/background.png /background.png

hoping that might mean "fall back to the cache copy if you can't get a new one", but in that configuration the browser doesn't try to request the resource if it's online.

Another possibility I considered was

CACHE:
/offline-background.png

FALLBACK:
/background.png /offline-background.png

but having two different names for the same resource -- and having the same resource requested twice (once for the img src="background.png" and once for the cached offline copy) -- seemed like an unattractive hack.

I could also make an arbitrary change to the manifest when background.png changes, but that would cause the browser to check everything in the manifest.

Is it possible to get this "use what I have unless I can get a new one" pattern from an HTML5 manifest? This seems like a reasonable pattern, so I'd think there'd be a clean way to do it. If not, can anyone suggest another approach? Thanks in advance!

EDIT: The original question referred to "news.json", implying that the resource was being retrieved by JavaScript, but I've changed it to "background.png" to make it clearer that I'd like to do this with any resource used by a page.


Solution

  • The best way to manage the caching yourself is to stick it into local storage. You should be able to simply drop the JSON from your news feed straight into a single variable. When you request the /news.json file only update the cached copy of it on a 200 response, in the rest of your app always use the copy in local storage.