Browser caching strategies are primarily used to improve webpage loading speed, reduce server load, and save bandwidth. The following are the main browser caching strategies:
-
Strong Cache
Expires: This header is used in HTTP/1.0 to specify the expiration time of the resource. If the current time is before the Expires time, the browser directly uses the cached resource without sending a request to the server.Cache-Control: Introduced in HTTP/1.1, it is more flexible than Expires. Common directives includemax-age(maximum valid time for the resource),no-cache(always verify with the server),no-store(completely do not cache), etc. Ifmax-ageis set and the cache is valid, the browser directly uses the local cache.
-
Negotiated Cache
Last-ModifiedandIf-Modified-Since: The server includes theLast-Modifiedheader in the response to indicate the last modification time of the resource. On subsequent requests, the browser sends the value viaIf-Modified-Sinceto the server, which then checks if the resource has been updated.ETagandIf-None-Match: ETag is a unique identifier for the resource, which changes when the resource is modified. The browser stores the ETag of the resource and sends it viaIf-None-Matchon subsequent requests to check if the resource has been updated. If the server confirms no update, it returns a 304 status code, and the browser uses the local cache; if the content has been updated, it returns a 200 status code with the new resource content.
-
Pre-Caching
- Service Workers: They can intercept network requests and dynamically cache or restore resources. This enables effective offline experiences and fine-grained control over caching strategies.
-
Memory and Disk Cache Browsers typically cache resources in memory or on disk:
- Memory Cache: Stored in memory, it offers fast access speed but is only valid during the browser session.
- Disk Cache: Stored on the disk, it has slower access speed but remains available even after the browser is closed.
For example, suppose you visit a frontend website where the CSS file is configured with strong caching, Cache-Control set to max-age=3600. This means that for the next hour, if you revisit the website, the browser directly uses the locally cached CSS file without requesting the server again, thus speeding up page loading. For the news section of the website, negotiated caching may be used. On subsequent visits, it checks if the content has been updated using ETag or Last-Modified information to ensure users always see the latest content, while reducing unnecessary resource transfers when the content has not been updated.