What's the difference between using the Service Worker Cache API and regular browser cache?

Service WorkerProgressive Web-Apps

Service Worker Problem Overview


In my Progressive Web App, should I be using the Cache API in a service worker for my static assets, or should I just rely on the browser's native cache control for these? What's the difference?

Service Worker Solutions


Solution 1 - Service Worker

A major advantage of the service worker cache API is that it gives you more detailed control than the built-in browser cache does. For example, your service worker can cache multiple requests when the user first runs your web app, including assets that they have not yet visited. This will speed up subsequent requests. You can also implement your own cache control logic, ensuring that assets that are considered important are kept in the cache while deleting less-used data.

Solution 2 - Service Worker

The primary difference is control. Browser cache is driven off Cache-Control headers, which is good, until its not. There are all sorts of strategies to manage how network addressable resources are cached; private, public; time to live, etc.

With service worker caching you can programmatically control how those assets are persisted. But that means the burden is on you.

Browser cache is what I consider unreliable. The browser will automatically purge assets based on device storage availability. For example, iPhones used to ignore caching for any resource over 25kb. Today I think they are just very aggressive.

I know the Facebook team did a study a few years back and found only 25% of the files they expected browsers to cache based on headers were cached. This meant there was extra network traffic and server activity.

This is why service worker caching is the better choice. Don't go removing your cache headers, just don't lean on them.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe MariniView Question on Stackoverflow
Solution 1 - Service WorkerJoe MariniView Answer on Stackoverflow
Solution 2 - Service WorkerChris LoveView Answer on Stackoverflow