Sobes.tech
Middle+

How does resource caching work in the browser — how does the browser decide whether to take from cache or load anew, and how to manage this? What are the caching methods, including Service Worker?

sobes.tech AI

Answer from AI

The browser caches resources (HTML, CSS, JS, images, etc.) to speed up loading and reduce network load. When a request is made again, the browser decides whether to use the cache or fetch the resource anew based on HTTP headers and caching policies.

How the browser decides to use cache or not

  • Cache-Control — the main header that sets caching rules. For example, max-age=3600 means the resource is considered fresh for an hour.
  • Expires — an outdated but still supported header with the expiration date of the resource.
  • ETag — a unique identifier for the resource version. On subsequent requests, the browser sends If-None-Match with the ETag, and the server responds with 304 Not Modified if the resource hasn't changed.
  • Last-Modified — the date of the last modification of the resource. Similar to ETag, the browser sends If-Modified-Since.

If the resource is fresh and not expired, the browser uses the cache. If not, it makes a request to the server with a condition to check for changes.

Cache management

  • Configure headers on the server (e.g., in nginx, Apache, or backend application).
  • Use resource versioning (e.g., hash in filename) to control updates.
  • In HTML, you can use <meta http-equiv="Cache-Control" content="no-cache">, but this is less effective.

Caching methods

  1. HTTP caching — standard caching via headers.
  2. LocalStorage / IndexedDB — for storing data on the client side, not resources.
  3. Service Worker — a script that operates between the network and the application, allowing full control over caching and creating offline applications.

Example of a Service Worker for resource caching:

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/',
        '/styles.css',
        '/script.js',
        '/image.png'
      ]);
    })
  );
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

Thus, Service Worker allows intercepting requests and serving resources from the cache, even when the network is unavailable.