TIL - Offline

What follows is notes from a class. Incomplete thoughts & code that probably will only make sense to me. Given enough time, even that may be a stretch! Reference at your own risk 😂

Slides

Web Workers

They put some actions on a second thread in the browser, so you can do background work while the webpage is doing its thing.

Demo app and accompanying GitHub repo to see what’s happening in the code.

Here’s another demo app and the code.

Service Workers

A service worker is a type of worker which works with the Cache API to fetch and cache assets like HTML, images, CSS, JS, etc.

This site as well as CanIUse each give an overview of which parts of the API are available and which browsers they’re compatible with.

Service worker scripts need to be in the root directory and most often won’t work if they’re within project folders.

To test these you have to be running a server, even localhost.

Every change to a service worker file makes it recognized as a new service worker, which will be queued.

skipWaiting used to be problematic apparently but now it’s not so much…it’s probably fine to use.

claimClients is a way to add a service worker to already-open tabs if they’re old, on the same domain, and don’t have the service worker installed or registered.

IndexedDB

This can be like a backup database for when the app is offline.

Its native API isn’t great (see Codepen demo) but there are wrappers which make it easier to use:

Performance API

Apparently there is a performance API to let you test a site’s performance!

Workbox

Because all of this above can be a bit convoluted to figure out the best approach, Google created Workbox. The idea is to combine it with Webpack so that you have less to manage manually in your service workers.

It uses human language method names that make working with service workers more accessible.

Questions To Follow Up

  • Can you do this with big media files?

Different browsers have different size limits for how much you can store in cache. Of course it also depends on the capacity of the user’s computer. Here’s another walkthrough of the limits.

  • Can you put some bits online and leave media files for download on demand?
  • Do I have to have all of my assets in my app to do this or can I use a 3rd party service like Cloudinary for images?

Yes, a.

More Follow Up

Here is a course to learn about PWAs from beginning to end, in more detail. Or it also might be fun to learn it by playing a game instead.