>> Web Performance

Make pages load quickly, stay responsive, and feel fast on real devices.

Caching Strategies (Cache-Control, SW)

Web Performance Lesson 5 of 10 ~10 min read

Overview

Cache static assets and API responses intentionally.

Caching Strategies (Cache-Control, SW) is about user experience under real-world limits. Fast pages prioritize important work, avoid unnecessary bytes, and measure changes instead of guessing.

Core Ideas

  • Measure Caching Strategies (Cache-Control, SW) with a repeatable baseline before changing code.
  • Optimize the resource or task that users feel first.
  • Avoid moving work around if it does not improve a real metric.
  • Keep budgets visible so regressions are caught early.

Step by Step

  1. Record the current Caching Strategies (Cache-Control, SW) metric or resource size.
  2. Make one optimization at a time so the result is attributable.
  3. Retest with throttling and compare the before/after numbers.
  4. Keep the change only if the metric improves without hurting usability.

Beginner Explanation

Caching Strategies (Cache-Control, SW) explains how repeat visits become faster when browsers can reuse files instead of downloading them again.

Caching works best when asset filenames are versioned and cache headers match how often the file changes.

Beginners should learn the difference between HTML, static assets, API responses, and service worker caches because each needs a different strategy.

Before You Start

  • Before practicing Caching Strategies (Cache-Control, SW), choose one page and one user task to measure.
  • Record the current result before changing code so you have a baseline.
  • Open the Network and Performance panels and reload with cache disabled once, then reload with cache enabled once.
  • Note the largest resources, longest tasks, render-blocking files, layout shifts, and slow requests.
  • Change only one performance variable at a time so the before and after result makes sense.

Key Performance Concepts

  • Versioned static assets can use long cache lifetimes.
  • HTML usually needs shorter caching because it points to current assets.
  • API responses should match data freshness needs.
  • Service workers need update and fallback strategies, not only cache-first logic.

Plain-English Glossary

  • LCP: Largest Contentful Paint, usually the moment the main visible content appears.
  • INP: Interaction to Next Paint, a measure of how responsive the page feels after interactions.
  • CLS: Cumulative Layout Shift, a measure of unexpected visual movement.
  • Render-blocking: a file or task that delays the browser from painting useful content.
  • Main thread: the browser thread that runs JavaScript, style, layout, painting, and many user interactions.
  • Long task: main-thread work that takes long enough to delay interaction or rendering.
  • Waterfall: the Network panel timing view that shows request order, waiting, transfer, and blocking.
  • Cache hit: a resource loaded from browser or intermediary cache instead of downloaded again.

What You Will Learn

  • Explain which user-visible delay or instability Caching Strategies (Cache-Control, SW) improves.
  • Read a Network or Performance trace and point to the likely bottleneck.
  • Apply one small optimization in the editor or a real page and compare before and after.
  • Avoid fixes that improve one metric while making accessibility, reliability, or maintainability worse.

Where You Use This in Real Projects

You use Caching Strategies (Cache-Control, SW) on home pages, article pages, product pages, dashboards, admin tools, checkout flows, search pages, media pages, and any page with images, fonts, scripts, API data, or third-party tags.

Performance work is especially important on mobile devices, slower CPUs, weak networks, high-latency connections, and pages with many scripts or images.

In real projects, the best workflow is baseline, hypothesis, focused change, retest, document the result, and add a budget or regression check.

Browser and Measurement Notes

  • Local fast machines can hide problems that appear on mobile phones and slower networks.
  • Disable cache for first-load debugging, then enable cache to understand repeat visits.
  • Run tests multiple times because network and CPU noise can change single-run numbers.
  • Use lab tools for debugging and real user data for production priority decisions.
  • Measure the same page state each time, such as logged out, logged in, empty data, or full dashboard.

Code Example

Cache-Control: public, max-age=31536000, immutable

self.addEventListener('fetch', event => {
  if (event.request.destination === 'image') {
    event.respondWith(
      caches.open('images-v1').then(cache =>
        cache.match(event.request).then(cached => cached || fetch(event.request))
      )
    );
  }
});

Another Example

# Versioned assets can be cached for a long time.
Cache-Control: public, max-age=31536000, immutable

# HTML changes more often because it references the latest assets.
Cache-Control: no-cache

More Practice Examples

Example 1: Measure one interaction

const button = document.querySelector('#measureButton');
const output = document.querySelector('#metricOutput');

button?.addEventListener('click', () => {
  performance.mark('interaction-start');

  requestAnimationFrame(() => {
    performance.mark('interaction-painted');
    performance.measure('button interaction', 'interaction-start', 'interaction-painted');
    const measure = performance.getEntriesByName('button interaction').at(-1);
    output.textContent = `${measure.duration.toFixed(2)} ms`;
  });
});
  • performance.mark creates named timestamps in the browser.
  • requestAnimationFrame waits until the browser is ready to paint.
  • Measuring one interaction is easier to understand than measuring the whole app at once.

Example 2: Reserve space for media

<img src="/lesson-card.webp"
     width="640"
     height="360"
     alt="Lesson card preview"
     loading="lazy"
     decoding="async">
  • width and height let the browser reserve space before the image loads.
  • loading="lazy" is useful for images below the first viewport.
  • decoding="async" lets image decoding avoid blocking other rendering work.

Example 3: Keep noncritical code out of the first load

const loadChartButton = document.querySelector('#loadChart');

loadChartButton?.addEventListener('click', async () => {
  const module = await import('./chart.js');
  module.renderChart();
});
  • The chart code is not downloaded until the user asks for it.
  • Dynamic import is useful for heavy features below the first task.
  • Do not split tiny code so much that extra requests become the new problem.

Example Explained

  • The Caching Strategies (Cache-Control, SW) example focuses on one measurable performance problem instead of trying to optimize everything at once.
  • The code either reduces bytes, prevents blocking work, reserves layout space, improves cache reuse, or measures a user-visible metric.
  • The important part is the before and after comparison, because performance work without measurement can become guesswork.
  • A good fix should improve the target metric without hurting accessibility, content quality, analytics needs, or long-term maintainability.

How to Read This Example

  1. Identify what the example is improving: load time, response time, layout stability, transfer size, or perceived waiting.
  2. Find the resource, metric, or browser API being used.
  3. Predict what should improve before running the code.
  4. Run the example, record the result, then change one value and compare again.
  5. Connect the result back to Caching Strategies (Cache-Control, SW) by explaining what the user would notice.

Code Editor Example

Open a ready-made starter for this lesson in the live HTML, CSS, and JavaScript editor. You can change the code, then click Run to see the result immediately.

Open in Code Editor

Checklist

  • Measure before and after every optimization.
  • Optimize the largest and most blocking resources first.
  • Test on a throttled network and a slower CPU profile.

Common Mistakes

  • Optimizing without a baseline measurement.
  • Loading important resources late while loading noncritical resources early.
  • Improving lab scores while ignoring real device behavior.

Do and Don't

  • Do: measure Caching Strategies (Cache-Control, SW) before and after changing code.
  • Do: optimize the biggest user-visible bottleneck first.
  • Do: keep image sizes, script cost, font loading, cache headers, and layout stability visible during review.
  • Don't: chase a perfect score while breaking accessibility, content, analytics, or maintainability.
  • Don't: preload, lazy-load, split, or cache everything blindly. Each technique has tradeoffs.

Practice Challenge

Apply the Caching Strategies (Cache-Control, SW) idea to one real page, record a before number, make one change, and record the after number.

Try These Changes

  • Change one image size or loading attribute and explain how it could affect LCP or CLS.
  • Add one artificial long task in the editor, then remove it and compare the measured interaction time.
  • Move one noncritical feature behind a button click or idle callback.
  • Add a simple budget for scripts, images, or total requests.
  • Write a short note explaining what metric improved and what tradeoff you accepted.

Quick Check

  • Question: What should you do before optimizing? Answer: Record a baseline measurement.
  • Question: Which metric tracks the main content appearing? Answer: LCP.
  • Question: Which metric tracks unexpected visual movement? Answer: CLS.
  • Question: Why can too much JavaScript hurt performance? Answer: It can block parsing, rendering, and interaction on the main thread.
  • Question: Why are budgets useful? Answer: They prevent gradual regressions as the site grows.

Debugging Checks

  • Use the Network panel to find large files, slow requests, blocked requests, and cache misses.
  • Use the Performance panel to find long tasks, layout shifts, expensive rendering, and delayed interactions.
  • Check whether images have correct dimensions, responsive sources, and suitable loading behavior.
  • Check whether scripts can be deferred, split, removed, or run after the first task.
  • Retest with throttling and repeat runs so one lucky result does not hide the real issue.

Mini Project

Build a caching plan for Caching Strategies (Cache-Control, SW): separate HTML, versioned CSS, versioned JS, images, fonts, and API responses with the cache rule each should use.

Mastery Check

  • You can say which metric Caching Strategies (Cache-Control, SW) improves and how you measured it.
  • You can explain the tradeoff of the optimization.
  • You can add a budget or regression check for the same issue.
Create a free account to save which lessons you've finished. Save my progress