HTTP缓存JS、CSS与图片时,浏览器读缓存是否仍需请求服务器?
Great question! This depends entirely on the HTTP caching rules set for those resources—let’s break it down into two key scenarios that cover most real-world cases:
1. Strong Caching (No Request Sent At All)
When a resource (JS, CSS, image) has a valid strong cache policy in place, the browser will skip the network entirely and load the resource directly from its local cache.
This behavior is controlled by two core HTTP response headers:
Cache-Control: The modern, preferred standard. It uses relative time to define cache validity (e.g.,Cache-Control: max-age=86400means the cache stays valid for 24 hours). You’ll also see values likepublic(allows shared caches like CDNs to store the resource) orprivate(restricts caching to the user’s browser only).Expires: An older header that uses an absolute timestamp (e.g.,Expires: Wed, 21 Oct 2025 07:28:00 GMT). Note thatCache-Controltakes priority overExpiresif both are present.
As long as the cache hasn’t expired, the browser won’t even initiate a network request for that resource—this is the fastest possible way to load content.
2. Negotiated Caching (Request Sent, But May Not Download New Content)
Once the strong cache period ends, or if the resource is configured with must-revalidate (via Cache-Control), the browser will send a validation request to the server. This isn’t a request for the full resource—it’s a check to see if the cached version is still up-to-date.
This uses paired header sets:
Last-Modified+If-Modified-Since: The server sendsLast-Modifiedwith the resource’s last update timestamp. When the cache expires, the browser sendsIf-Modified-Sincewith that timestamp. If the resource hasn’t changed, the server returns a304 Not Modifiedstatus, and the browser reuses its local cache.ETag+If-None-Match: A more precise alternative.ETagis a unique string (like a content hash) that identifies the resource’s current state. The browser sendsIf-None-Matchwith the cached ETag; if it matches the server’s current ETag, the server returns 304. If not, it sends the updated resource (200 OK) and updates the browser’s cache.
In this scenario, a request is sent, but you avoid re-downloading the entire resource unless it’s actually changed.
Bonus: Cache Busting for Updated Resources
For JS/CSS (which change more frequently than static images), teams often use cache busting—adding a unique hash to the filename (e.g., app.abc123.js instead of app.js). When the code updates, the hash changes, so the browser treats it as a completely new resource, skips the old cache, and sends a full request for the updated file. This ensures users get the latest version without waiting for cache expiration.
内容的提问来源于stack exchange,提问作者Steve Paul

