浏览器与服务器缓存
使用 HTTP 标头、服务工作线程和服务器端缓存机制,实现有效的缓存策略。
浏览器与服务器缓存 是 CoddyKit 上的免费 Web Performance Optimization & Lighthouse 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Performance Optimization & Lighthouse 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Caching: Speeding Up the Web
Imagine visiting a website. Every time, your browser has to download all the images, stylesheets, and scripts from scratch. That would be slow!
Caching solves this by storing copies of these resources closer to you, either in your browser or on an intermediate server. This means less data transfer and faster load times on subsequent visits.
Why Caching Matters
Efficient caching is crucial for web performance. It offers several key benefits:
- Faster Page Loads: Users get content quicker, improving their experience.
- Reduced Server Load: Your server doesn't have to send the same data repeatedly.
- Lower Bandwidth Costs: Less data transferred means lower costs for both users and providers.
- Offline Capabilities: Advanced caching can even allow users to browse content offline.
Two Types of Caching
Caching can happen in different places. We'll focus on two main types:
- Browser Caching (Client-Side): Resources are stored directly on the user's device. This is the fastest form of caching for returning visitors.
- Server-Side Caching: Resources are stored on the web server or a proxy server before they reach the user. This reduces the work the server has to do.
Browser Caching with HTTP Headers
How does a browser know what to cache and for how long? It relies on HTTP response headers sent by the web server. These headers act like instructions for the browser.
Key headers include Cache-Control, Expires, ETag, and Last-Modified. They dictate how long a resource is considered fresh and when it needs to be re-checked.
The Cache-Control Header
The Cache-Control header is the most powerful and flexible caching mechanism. It tells browsers and intermediate caches how to handle a resource.
Common directives include:
max-age=SECONDS: Cache for this many seconds.no-cache: Browser must revalidate with server before using cached copy.no-store: Never cache this resource.public/private: Can be cached by any cache or only by the user's browser, respectively.
Cache-Control Example
Here's an example of HTTP response headers for an image that can be cached publicly for one year (31,536,000 seconds). This tells the browser it's safe to use the local copy without checking the server for a long time.
HTTP/1.1 200 OK
Content-Type: image/jpeg
Cache-Control: public, max-age=31536000
Expires: Tue, 25 Nov 2025 10:00:00 GMT
ETag: "image-v123"Revalidation with ETag & Last-Modified
Even when a resource is cached, it might need to be revalidated. The ETag (entity tag) and Last-Modified headers help with this.
Last-Modified: The date and time the resource was last changed.ETag: A unique identifier (like a hash) for a specific version of a resource.
The browser sends these back to the server. If the resource hasn't changed, the server responds with a 304 Not Modified, saving bandwidth.
Service Workers: Advanced Caching
Beyond HTTP headers, Service Workers offer powerful, programmatic control over caching. A Service Worker is a JavaScript file that acts as a proxy between your browser and the network.
They can intercept network requests, cache responses using the Cache API, and serve content even when offline. This enables truly robust offline experiences and custom caching strategies.
Registering a Service Worker
To use a Service Worker, you first need to register it in your main JavaScript file. This code checks for Service Worker support and registers your sw.js file.
Once registered, the Service Worker can then define its own caching logic, like caching specific assets or entire pages.
// This code would be in your main.js file
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered with scope:', registration.scope);
})
.catch(error => {
console.log('SW registration failed:', error);
});
});
}Server-Side Caching Overview
Caching isn't just for browsers. Servers also use caching to reduce the load on databases and speed up response times. This can involve storing:
- Database Query Results: Avoid re-running complex queries.
- Rendered HTML Fragments: Serve parts of a page that don't change often.
- API Responses: Cache data fetched from other services.
Server-side caching is managed by your web server or application framework, often using tools like Redis or Memcached.
Caching Strategy Check
You've learned about various caching mechanisms. Let's test your understanding of HTTP caching headers.
Recap: Caching for Performance
We've covered how caching significantly boosts web performance. You learned about:
- Browser Caching: Using HTTP headers like
Cache-Control,ETag, andLast-Modified. - Service Workers: Providing powerful, programmatic control over client-side caching, enabling offline capabilities.
- Server-Side Caching: Reducing server load and speeding up dynamic content delivery.
Implementing effective caching strategies is a fundamental step towards building fast and resilient web applications.
常见问题解答
「浏览器与服务器缓存」课时是免费的吗?
是的 — 「浏览器与服务器缓存」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Performance Optimization & Lighthouse 课程的其余内容,请升级到 CoddyKit PRO。 Web Performance Optimization & Lighthouse 课程共包含 4 节课。
「浏览器与服务器缓存」这节课中我会学到什么?
使用 HTTP 标头、服务工作线程和服务器端缓存机制,实现有效的缓存策略。 你通过在浏览器中直接运行的动手代码来练习 Web Performance Optimization & Lighthouse,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Performance Optimization & Lighthouse 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Performance Optimization & Lighthouse 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「浏览器与服务器缓存」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Performance Optimization & Lighthouse 课中编写并运行代码吗?
能。每节 Web Performance Optimization & Lighthouse 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- HTTP/2 与 HTTP/3 基础
- 浏览器与服务器缓存
- 内容分发网络(CDN)
- 压缩与传输编码