Browser caching is primarily designed to improve webpage loading speed, reduce server load, and enhance user browsing experience. Browser caching can be categorized into the following types:
-
Strong Caching (HTTP Cache Control) Strong caching avoids sending requests to the server and directly fetches resources from the cache. This is achieved by setting the
Cache-ControlandExpiresheaders in the HTTP response.Cache-Control: This response header specifies multiple values, including:max-age=xxx: Indicates the resource expires after xxx seconds.no-store: Prevents caching; the server is requested every time.no-cache: The resource is not cached; a request is sent to the server each time to verify updates.
Expires: This is an absolute timestamp indicating when the resource expires.
-
Validation Caching (Validation Cache) Upon expiration of strong caching, the browser requests the server to verify if the resource has been updated. This is implemented using the
Last-Modified/If-Modified-SinceandETag/If-None-Matchheader pairs.Last-Modified/If-Modified-Since: The server specifies the last modification time viaLast-Modifiedin its response. The browser includesIf-Modified-Sincein subsequent requests; if no changes are detected, the server responds with a 304 status code, allowing the browser to continue using the cached resource.ETag/If-None-Match:ETagacts as a unique identifier for the resource, akin to a fingerprint. The browser sendsIf-None-Matchin requests; if the ETag matches, the server returns a 304 status code, and the browser continues using the cached resource.
-
Web Storage (Local Storage) This includes
localStorageandsessionStorage, enabling key-value pair storage on the client side.localStoragedata persists after the browser is closed, whereassessionStoragedata is cleared upon session termination. -
IndexedDB IndexedDB is a mechanism for storing substantial structured data in the browser, supporting the creation, reading, traversal, and search of database records. Operations are event-based, and unlike Web Storage, it provides more sophisticated data manipulation features.
-
Service Workers Service workers can intercept requests and utilize the cache API to handle responses. Developers can define custom caching strategies, such as serving cached fallback content when the network is unavailable.
For example, when a user initially accesses a webpage, the browser downloads all resources and determines caching based on HTTP headers. On subsequent visits, if resources have valid strong caching, the browser loads them directly from the cache without server requests, significantly enhancing page load speed. If strong caching expires, the browser employs the validation caching mechanism to check for updates with the server and decides whether to re-download or continue using the cached version.