mpen
mpen

Reputation: 283043

workbox-webpack-plugin -- how to download assets only when user Installs my app?

I'm trying to make my SPA installable on mobile phones. It doesn't have to be completely offline because it'll need to fetch data anyway, but I want to cache all the static assets (JS, CSS, icons).

I found the workbox-webpack-plugin and it seems to work pretty well so far. My app is installable now, however I want to tweak how it does the caching.

My app is already pretty efficient at chunking, only loading the resources it needs and utilizing the browser cache (using hashed filenames). It feels like a waste to throw that away to download everything when the user first visits the site.

Can I make so resources are only downloaded if the user installs my app? As in, it'll download whatever it hasn't already cached via navigating around the site when the user tries to add my app to their homescreen?

It looks like this in Chrome for Windows:

Upvotes: 0

Views: 152

Answers (1)

pate
pate

Reputation: 5263

It is possible but to the best of my knowledge there isn't a ready made solution. You'll need to write the code manually.

The basic idea would be:

  1. Generate an SW with a list of all the files that might need to be cached after installation
  2. Make the SW NOT cache anything by default
  3. Make the SW listen for a message using postMessage API
  4. Either when the user installs the app or when the app is launched from home screen, send a message from the page JS to the SW. In the SW, trigger caching of all the assets

I recommend you to read this https://web.dev/customize-install/ for more info about the installation process and its events, detection, and so forth.

Upvotes: 1

Related Questions