惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyberwarzone
Cyberwarzone
Jina AI
Jina AI
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
博客园 - 司徒正美
宝玉的分享
宝玉的分享
C
Check Point Blog
有赞技术团队
有赞技术团队
小众软件
小众软件
IT之家
IT之家
Vercel News
Vercel News
V2EX - 技术
V2EX - 技术
雷峰网
雷峰网
L
Lohrmann on Cybersecurity
Cloudbric
Cloudbric
Engineering at Meta
Engineering at Meta
Schneier on Security
Schneier on Security
P
Privacy International News Feed
Apple Machine Learning Research
Apple Machine Learning Research
W
WeLiveSecurity
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
J
Java Code Geeks
T
Threatpost
S
Secure Thoughts
T
Tailwind CSS Blog
V
V2EX
Attack and Defense Labs
Attack and Defense Labs
P
Palo Alto Networks Blog
S
Security @ Cisco Blogs
The GitHub Blog
The GitHub Blog
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
AWS News Blog
AWS News Blog
罗磊的独立博客
GbyAI
GbyAI
Blog — PlanetScale
Blog — PlanetScale
Microsoft Azure Blog
Microsoft Azure Blog
Forbes - Security
Forbes - Security
N
News | PayPal Newsroom
博客园 - 叶小钗
Hugging Face - Blog
Hugging Face - Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Webroot Blog
Webroot Blog
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Service Worker Caching Strategies: Cache-First, Network-First, and SWR
Ashish Kumar · 2026-05-15 · via DEV Community

Related: Network Optimization for SPAs and React Apps covers the broader network optimization picture including HTTP caching and API request optimization.

A service worker is a JavaScript file that runs in a background thread, separate from your main application. It intercepts every network request your page makes and can respond from cache, modify the request, or let it pass through to the network unchanged. For a returning visitor, a well-configured service worker means many requests never touch the network at all. The page loads from cache at local disk speed.

What this covers: What service workers can and cannot do, the three core caching strategies (cache-first, network-first, stale-while-revalidate), when each strategy is correct for which resource type, and how Workbox makes implementing these strategies practical without writing the interception logic by hand.

Diagram showing three caching strategies: cache-first serving from cache immediately, network-first checking network before cache, and stale-while-revalidate serving cache then updating in background.


What a service worker actually does

A service worker is registered by your application JavaScript and installed by the browser. Once installed, it intercepts all network requests made from pages on its origin. This includes requests for HTML, CSS, JavaScript, images, fonts, and API calls.

// Register the service worker from your main application
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js');
  });
}

Enter fullscreen mode Exit fullscreen mode

The service worker file (sw.js) runs in a separate worker thread. It has access to the Cache Storage API, which is separate from the HTTP cache the browser manages automatically. The Cache Storage API is under your complete control: you decide what to cache, when to cache it, how long to keep it, and when to delete it.

// Inside sw.js: intercept a fetch event and respond from cache
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(cachedResponse => {
      if (cachedResponse) {
        return cachedResponse; // Serve from cache
      }
      return fetch(event.request); // Fall through to network
    })
  );
});

Enter fullscreen mode Exit fullscreen mode

This is the basic cache-first pattern in raw form. Every real application needs more nuance: what if the cache is stale? What if certain resources should never be served from cache? What if the network is unavailable? Writing and maintaining all of this logic by hand is error-prone, which is why Workbox exists.


Strategy 1: Cache-First

Cache-first means: check the cache first. If a response is in cache, return it immediately without hitting the network. Only go to the network if the resource is not in cache.

Use this for: Versioned static assets. JavaScript bundles, CSS files, images, and fonts that have content hashes in their filenames (main-a1b2c3.js). When the content changes, the filename changes, so cached versions are never stale. The old cache entry becomes unreachable by the new URL and gets cleaned up during the next cache update.

Why it works for these resources: Versioned assets are safe to serve from cache forever because the filename is tied to the content. A browser serving main-a1b2c3.js from cache in six months will serve the exact same content that was served when the file was first cached. The application code that requests this file will either request the cached version (nothing changed) or request a different URL (the content changed and the new build output has a new hash).

// Workbox: cache-first for all versioned assets

registerRoute(
  // Match hashed JavaScript and CSS files
  ({ request, url }) =>
    request.destination === 'script' ||
    request.destination === 'style',
  new CacheFirst({
    cacheName: 'static-assets',
    plugins: [
      new ExpirationPlugin({
        maxAgeSeconds: 365 * 24 * 60 * 60, // 1 year
        maxEntries: 60,
      }),
    ],
  })
);

Enter fullscreen mode Exit fullscreen mode

What to avoid: Using cache-first for HTML documents or unversioned API endpoints. If your HTML is served from cache and you deploy a new version, users will continue loading the old HTML until the cache expires. HTML should use network-first or stale-while-revalidate so users always get current navigation and content structure.


Strategy 2: Network-First

Network-first means: try the network first. If the network succeeds, serve the response and update the cache. If the network fails (offline, timeout, server error), fall back to the cached version.

Use this for: HTML pages, API endpoints serving fresh data, and any resource where stale content would cause problems. The user always gets the freshest version when online. When offline, they get a reasonable fallback from cache.

// Workbox: network-first for HTML pages

registerRoute(
  ({ request }) => request.mode === 'navigate', // HTML navigation requests
  new NetworkFirst({
    cacheName: 'pages',
    networkTimeoutSeconds: 3, // Fall back to cache if network takes more than 3 seconds
    plugins: [
      new ExpirationPlugin({
        maxEntries: 50,
        maxAgeSeconds: 30 * 24 * 60 * 60, // Keep cached pages for 30 days
      }),
    ],
  })
);

Enter fullscreen mode Exit fullscreen mode

The networkTimeoutSeconds option is important for offline-capable applications. Without it, network-first will wait indefinitely for a network response even when the user is offline, only falling back to cache after the connection eventually times out (which can take 30-60 seconds). Setting a 3-second timeout means users in poor network conditions get a cached response quickly.

For API endpoints serving user-specific or time-sensitive data:

// Workbox: network-first for API calls
registerRoute(
  ({ url }) => url.pathname.startsWith('/api/'),
  new NetworkFirst({
    cacheName: 'api-responses',
    networkTimeoutSeconds: 5,
    plugins: [
      new ExpirationPlugin({
        maxEntries: 100,
        maxAgeSeconds: 24 * 60 * 60, // Cache API responses for 1 day
      }),
    ],
  })
);

Enter fullscreen mode Exit fullscreen mode

The cached API response is not perfectly fresh, but for most use cases it is better than showing an error page when the network is unavailable.


Strategy 3: Stale-While-Revalidate

Stale-while-revalidate means: serve the cached version immediately (stale), and simultaneously fetch a fresh version from the network in the background (revalidate). The next request gets the fresh version.

Use this for: Resources where some staleness is acceptable and speed is more important than absolute freshness. Navigation assets that change infrequently, avatar images, icon sets, and any resource where showing a slightly old version on the current visit is fine as long as the next visit gets the update.

// Workbox: stale-while-revalidate for images

registerRoute(
  ({ request }) => request.destination === 'image',
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
      }),
    ],
  })
);

Enter fullscreen mode Exit fullscreen mode

The user experience for stale-while-revalidate: on the first visit, there is no cache, so the image loads from the network normally. On subsequent visits, the cached image appears instantly. In the background, the service worker fetches a fresh version from the network. If the image changed, the fresh version replaces the cached version. On the visit after that, the updated image appears instantly.

Why this is powerful for most non-critical resources: Users almost never notice if an avatar image or icon set is one version old. What they notice is speed. Stale-while-revalidate gives them cache speed on every visit while keeping the cache reasonably fresh.


Precaching: caching at install time

All three strategies above are runtime caching: resources get cached when the user visits pages that request them. Precaching is different: you tell Workbox which resources to cache immediately when the service worker installs, before the user has visited any page.

Precaching is used for the application shell: the minimal HTML, CSS, and JavaScript needed to render a working (possibly empty) UI. When the user opens the app, even before any network requests complete, the service worker serves the precached shell and the app renders immediately.

// Workbox: precache the app shell at install time

// This list is generated by Workbox at build time (via workbox-build or the Vite plugin)
// It contains all files from your build output with their content hashes
precacheAndRoute(self.__WB_MANIFEST);

Enter fullscreen mode Exit fullscreen mode

The self.__WB_MANIFEST placeholder is replaced at build time by the Workbox build tool with an array of all your static assets and their content hashes. When a user installs the service worker for the first time, Workbox fetches all these assets and caches them. On subsequent visits, they are served from cache instantly.


Setting up Workbox in a Vite project

The easiest setup for modern projects uses the vite-plugin-pwa plugin, which integrates Workbox configuration into the Vite build process:

// vite.config.ts

  plugins: [
    VitePWA({
      registerType: 'autoUpdate',
      workbox: {
        // Precache all files matching these patterns from the build output
        globPatterns: ['**/*.{js,css,html,ico,png,webp,svg,woff2}'],

        // Runtime caching rules
        runtimeCaching: [
          // Cache-first for versioned assets
          {
            urlPattern: /\.(?:js|css)$/,
            handler: 'CacheFirst',
            options: {
              cacheName: 'static-resources',
              expiration: {
                maxAgeSeconds: 365 * 24 * 60 * 60,
              },
            },
          },
          // Network-first for API calls
          {
            urlPattern: /^https:\/\/api\.example\.com\//,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'api-cache',
              networkTimeoutSeconds: 5,
              expiration: {
                maxEntries: 200,
                maxAgeSeconds: 24 * 60 * 60,
              },
            },
          },
          // Stale-while-revalidate for images
          {
            urlPattern: /\.(?:png|jpg|webp|svg|gif)$/,
            handler: 'StaleWhileRevalidate',
            options: {
              cacheName: 'images',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 30 * 24 * 60 * 60,
              },
            },
          },
        ],
      },
    }),
  ],
};

Enter fullscreen mode Exit fullscreen mode

This configuration handles the most common case: versioned JavaScript and CSS with cache-first, API responses with network-first and a 5-second fallback timeout, and images with stale-while-revalidate.


What service workers cannot cache

Opaque responses. Requests to third-party origins without CORS headers return "opaque" responses. Opaque responses can be cached, but their size is counted as 7MB regardless of actual size due to security restrictions. Caching too many opaque responses can exhaust cache storage limits.

Range requests. Video streaming uses HTTP range requests to fetch specific byte ranges. Service workers can intercept these, but handling them correctly requires specific logic. The default Workbox strategies do not handle range requests.

Resources requiring authentication in every request. If a resource requires a fresh token in each request and you cannot cache the token, you cannot meaningfully cache the resource either.


The return visit experience

After a service worker is installed and caching is running correctly, a returning visitor's experience is qualitatively different from a first visit:

  1. User opens the app
  2. Service worker intercepts navigation request
  3. Precached index.html returns instantly from service worker cache
  4. Browser parses HTML, requests JavaScript and CSS
  5. Service worker intercepts those requests, returns from cache instantly
  6. App renders with no network requests at all
  7. In background, service worker fetches fresh API data
  8. UI updates with fresh data when background fetch completes

Steps 1 through 6 complete in under 100ms on most devices, regardless of network speed, because no network requests were made. The perceived load time is the time to render from cache, not the time to fetch from a server.

This is the correct mental model for why service workers matter: not as a way to make network requests faster, but as a way to eliminate network requests entirely for everything that can safely be served from cache.


Read the original article on Renderlog.in:
https://renderlog.in/blog/service-worker-caching-strategies-workbox/

If you found this helpful, I've also built some free tools for developers and everyday users. Feel free to try them once:

JSON Tools: https://json.renderlog.in
Text Tools: https://text.renderlog.in
QR Tools: https://qr.renderlog.in