CodePark/ questions / Web workers & service workers
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Web workers & service workers

Explain the cache-first, network-first and stale-while-revalidate strategies, and briefly what makes a site a PWA.

These are three ways a service worker can choose between the cache and the network.

Cache-first: look in the cache first, and only go to the network on a miss. It is fast and works offline. But it can serve outdated content, so it suits versioned assets, fonts and images.

Network-first: try the network first. Fall back to the cache when offline or after a timeout. Content stays fresh, so it suits HTML and API responses. But it is only as fast as the network.

Stale-while-revalidate: respond from the cache straight away. Then fetch an update in the background and store it for next time. It balances speed and freshness, for things like avatars or non-critical API data.

A PWA (progressive web app) is a website that can be installed like an app and can work offline. It has:

  • HTTPS
  • a web app manifest (a file with the name, icons and display mode)
  • usually, a service worker
  • Cache-first gives speed and offline support, but it risks stale data.
  • Network-first keeps content fresh and uses the cache as a fallback.
  • Stale-while-revalidate responds instantly and updates in the background.
  • A PWA uses HTTPS, a manifest and a service worker, and it can be installed.