Belajar
← Semua pelajaran

Cara kerja HTTP caching

Ambil, pakai ulang, lalu revalidasi

Browser
Cache
Server

browser-cache.js

// yang dilakukan cache browser untuk tiap requestasync function load(url) {  const hit = cache.get(url);  if (!hit) return fetch(url);  if (hit.age < hit.maxAge) return hit.body;  const res = await fetch(url, {    headers: { "If-None-Match": hit.etag },  });  if (res.status === 304) return hit.body;  return res.body;}

server.js

app.get("/app.css", (req, res) => {  const etag = `"${hash(css)}"`;  if (req.headers["if-none-match"] === etag) {    return res.status(304).end(); // tanpa body  }  res.set("Cache-Control", "max-age=60");  res.set("ETag", etag);  res.send(css);});

Pilih header Cache-Control lalu geser jamnya

Server mengirim app.css denganmax-ageno-cacheno-storeimmutable
Waktu sejak fetch pertama0 s
Sementara itu, di serverFile samaFile berubah
Halaman meminta app.css lagi
request
response
diunduh
kamu dapat

browser-cache.js

// header: Cache-Control yang dibawa file-nyaswitch (header) {  case "max-age=60":    if (age < 60) return cached.body;    return revalidate(cached);  case "no-cache":    return revalidate(cached);  case "no-store":    return fetch(url); // tidak menyimpan salinan  case "max-age=31536000, immutable":    return cached.body;}

browser-cache.js

async function revalidate(cached) {  const res = await fetch(url, {    headers: { "If-None-Match": cached.etag },  });  if (res.status === 304) return cached.body;  return res.body; // 200 dengan file baru}

Nama file ber-hash mengirim update menembus cache setahun

Tambah satu baris ke app.css
app.css
Hasil build
hash
file
index.html
Pengunjung yang kembali, dengan file minggu lalu di-cache setahun

HTML-nya sendiri tidak bisa di-cache setahun. Ia pakai no-cache, jadi selalu melihat nama terbaru

build.js

// saat build, beri nama tiap file sesuai isinyaconst hash = contentHash(css).slice(0, 8);const name = `app.${hash}.css`;write(`dist/assets/${name}`, css);html = html.replace("app.css", name);

server.js

// file ber-hash tidak pernah berubah, jadi simpan setahunapp.use("/assets", express.static("dist/assets", {  maxAge: "1y", immutable: true,})); // HTML selalu cek ulang, jadi ia melihat nama baruapp.get("/", (req, res) => {  res.set("Cache-Control", "no-cache");  res.sendFile("dist/index.html");});

Topik

Berikutnya: Cara kerja CDN

Buka pelajaran