乐闻世界logo
搜索文章和话题

What are the caching strategies of browsers?

2024年8月5日 12:50

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:

  1. 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 include max-age (maximum valid time for the resource), no-cache (always verify with the server), no-store (completely do not cache), etc. If max-age is set and the cache is valid, the browser directly uses the local cache.
  2. Negotiated Cache

    • Last-Modified and If-Modified-Since: The server includes the Last-Modified header in the response to indicate the last modification time of the resource. On subsequent requests, the browser sends the value via If-Modified-Since to the server, which then checks if the resource has been updated.
    • ETag and If-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 via If-None-Match on 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.
  3. 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.
  4. 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.

标签:前端Browser