Code Splitting and Lazy Loading for Large SPAs
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Prompt
Your web application currently ships a single 6 MB client-side JavaScript bundle for a large Single-Page Application (SPA), pushing mobile Time to Interactive (TTI) past 9 seconds. To cut startup latency, you are leading an effort to break the monolith apart using build-time code splitting and on-demand lazy loading.
Walk through your end-to-end architectural plan across four dimensions:
- Choosing split boundaries: How do you determine where to cut the bundle, and what are the trade-offs between route-level chunks and component- or feature-level chunks?
- Async loading UX & visual stability: When a user navigates to or opens UI backed by an unfetched chunk, how do you handle pending states cleanly without causing jarring layout shifts?
- Chunk caching & live deployments: Once the app is split into dozens of versioned files, how do you configure long-lived browser caching, and how do you protect users who already have an older tab open when a fresh deployment publishes new chunk filenames?
- Production verification: Which field telemetry metrics confirm that startup speed genuinely improved for real users without shifting main-thread stalls or interaction stutter into later sessions?
Scope & Expectations
- Compare route-based and feature/component-based splitting boundaries, and explain how eager loading,
modulepreload, and speculativeprefetchprevent cascading network waterfalls. - Describe concrete UX patterns—geometry-matched skeletons, non-blocking view transitions, and localized error recovery—that keep Cumulative Layout Shift (CLS) near zero.
- Specify immutable content-hashed caching headers alongside multi-layered defenses against mid-session deployment version skew.
- Identify Real User Monitoring (RUM) Core Web Vitals and custom chunk-loading metrics that detect both initial-load wins and post-load main-thread jank.
Step-by-step walkthrough
Audit why a 6 MB bundle takes over 9 seconds
A Single-Page Application (SPA) is a web app that loads a single HTML shell once and uses JavaScript in the browser to render screens and handle page transitions without full browser reloads. Time to Interactive (TTI) measures how long it takes from navigation start until the page displays useful content and its main thread is free enough to respond quickly to user taps or clicks.
Every byte of JavaScript taxes a mobile device three times before the screen becomes interactive: first downloading over the radio, then parsing and compiling into bytecode, and finally executing on the browser's single main thread. Using decimal networking units (
1 MB = 1,000,000 bytes,1 Mbps = 1,000,000 bits/s) and assuming Brotli or Gzip compresses 6 MB of raw JavaScript by 4x down to 1.5 MB on a 1.5 Mbps mobile connection:Monolithic 6 MB bundle (1.50 MB compressed): 1. Download: 1.50 MB * 8 bits/byte = 12.0 Mbit -> 12.0 Mbit / 1.5 Mbps = 8.00 s 2. Parse/Run: 6 MB of unpacked JS on a mid-tier phone CPU ≈ 2.0–3.0 s Total TTI: ≈ 10.0–11.0 s Split initial shell (1.2 MB raw -> 300 KB compressed): 1. Download: 0.30 MB * 8 bits/byte = 2.4 Mbit -> 2.4 Mbit / 1.5 Mbps = 1.60 s 2. Parse/Run: 1.2 MB of unpacked JS ≈ 0.5–0.7 s Total TTI: ≈ 2.1–2.3 sBefore choosing split points, measure what is inside the 6 MB bundle using a bundle visualizer (
webpack-bundle-analyzer,rollup-plugin-visualizer, orsource-map-explorer) and the Chrome DevTools Coverage tab (which highlights bytes downloaded but never executed during initial load). Remove dead weight before deferring it: enable tree shaking (a bundler step that drops exported functions and modules your app never imports), replace bloated utility libraries, and stop shipping legacy polyfills to modern browsers.1. Strategy for boundaries: route splitting vs. feature splitting
Code splitting breaks one monolithic bundle at build time into multiple smaller
.jsfiles called chunks. Lazy loading defers downloading a non-critical chunk until (or shortly before) the user actually needs it.Before (1 monolithic bundle): [ app-monolith.js: Shell + Dashboard + Billing + AuditLog + ChartLib + SpreadsheetGrid (6.0 MB) ] After (initial shell + vendor + route & feature chunks): Initial load: [ vendor-react.js (180 KB) ] + [ app-shell-and-dashboard.js (420 KB) ] Route chunks: [ route-billing.js ] [ route-audit-log.js ] [ route-reports.js ] Feature chunks: [ spreadsheet-grid.js ] [ pdf-exporter.js ]Compare the two primary boundary strategies:
- Route-based splitting places each URL route (
/dashboard,/billing,/reports) into its own chunk.- Pros: Maps cleanly to URL navigation where users naturally expect a brief transition, requires minimal refactoring, and immediately prevents
/dashboardvisitors from downloading/audit-logor/billing. - Cons: Too coarse on its own. If
/dashboardimports a 700 KB spreadsheet grid hidden inside a secondary drawer, every/dashboardvisitor still downloads those 700 KB upfront.
- Pros: Maps cleanly to URL navigation where users naturally expect a brief transition, requires minimal refactoring, and immediately prevents
- Feature- or component-based splitting lazy-loads heavy, conditional UI inside a single page—such as a spreadsheet editor, interactive map, chart library, PDF viewer, modal dialog, or below-the-fold widget.
- Pros: Strips heavy, rarely triggered dependencies out of popular routes.
- Cons: The network fetch happens mid-interaction (for example, when clicking "Open Grid"), and every split boundary requires thoughtful loading and error UI.
A practical rule is to split wherever
chunk_size * P(not needed in session)is large. A 500 KB PDF exporter used in 5% of sessions saves 500 KB in the other 95% of sessions; splitting a 3 KB button used everywhere only adds request overhead. Start with route-based splitting, keep everything needed for the initial screen in the entry chunk, isolate stable framework libraries (react,react-dom) into a dedicated vendor chunk, and then add component-level splits for heavy conditional features:import { lazy, Suspense } from "react"; import { Routes, Route } from "react-router-dom"; // Route split: downloaded only when navigating to /billing const BillingPage = lazy(() => import("./pages/BillingPage")); // Feature split: downloaded only when the user opens the inline grid editor const SpreadsheetGrid = lazy(() => import("./grid/SpreadsheetGrid")); function App() { return ( <Suspense fallback={<PageSkeleton />}> <Routes> <Route path="/billing" element={<BillingPage />} /> </Routes> </Suspense> ); } function ReportPanel({ isEditingGrid }) { if (!isEditingGrid) return <ReportSummary />; return ( <Suspense fallback={<div style={{ minHeight: 280 }} aria-busy="true" />}> <SpreadsheetGrid /> </Suspense> ); }- Route-based splitting places each URL route (
Avoid import waterfalls with preload and prefetch
Lazy loading should not mean waiting passively until the user clicks. Worse, nested dynamic imports create an import waterfall—a chain where chunk A must finish downloading and executing before the browser even discovers it needs chunk B, which then discovers chunk C, stacking network round-trip times (RTT) end-to-end:
Import waterfall (150 ms RTT per hop -> 450 ms of pure latency before C starts): |-- chunk A --| |-- chunk B --| |-- chunk C --| Parallel modulepreload / prefetch (150 ms RTT total): |-- chunk A --| |-- chunk B --| |-- chunk C --|Use the browser's three loading priorities intentionally:
- Eager (in the entry bundle): Critical shell, router, and content needed to paint the initial screen.
<link rel="preload">/<link rel="modulepreload">: High-priority parallel download for sub-dependencies required on the current route so they never waterfall. Modern bundlers like Vite emitmodulepreloadtags automatically for a lazy chunk's static sub-imports.<link rel="prefetch">: Low-priority background download during browser idle time for chunks the user is likely to visit next. Trigger prefetches on strong intent signals—such as hovering or focusing a nav link (~100–300 ms head start before click) or scrolling a link into the viewport—and skip speculative prefetching when the user enables data-saver mode (navigator.connection?.saveData).
2. Manage loading states and eliminate layout shift
When a user triggers an asynchronous chunk load, the UI must feel responsive and never jump around when the code arrives. Cumulative Layout Shift (CLS) is a browser metric that penalizes unexpected movement of visible elements; a score of
0.1or lower is considered good.The browser computes a single layout shift score as
impact_fraction * distance_fraction. Suppose an unstyled lazy banner loads without reserved height, pushing text that occupied the top 50% of the screen down by 25% of the viewport height:Union of affected area (old [0%..50%] + new [25%..75%]): impact_fraction = 0.75 Vertical distance moved (25% of viewport height): distance_fraction = 0.25 Layout shift score: 0.75 * 0.25 = 0.1875 (> 0.10 limit!)Shifts within 500 ms of a discrete user input (a click, tap, or key press—not scrolling or hovering) are excluded from CLS, meaning any lazy chunk that takes longer than 500 ms on a slow mobile link directly hurts CLS unless space is reserved.
Apply four UX safeguards:
- Reserve exact geometry with skeletons: Give
<Suspense>fallbacks matching dimensions (min-height, fixed height, oraspect-ratio) so swapping the placeholder for the loaded component moves surrounding elements by 0 pixels. - Keep the current view interactive during route transitions: Wrap route navigations in React's
startTransition(and delay spinners by ~150–200 ms with a subtle top progress bar) so fast cached loads never cause a jarring flash of blank skeleton UI. - Never inject lazy content above what the user is reading: Reserve the slot upfront or append below the viewport, and animate transitions using GPU-composited
opacityandtransformrather thanheightortop. - Wrap lazy boundaries in an Error Boundary: An Error Boundary is a component that catches JavaScript or chunk-loading failures inside its child tree and displays a localized retry UI instead of a blank screen. Note that
React.lazycaches a rejected dynamicimport()promise permanently on that component instance, so a retry helper should retry inside theimport()wrapper before rejecting (or trigger a controlled page reload).
- Reserve exact geometry with skeletons: Give
3. Caching, content hashes, and surviving deploy version skew
To cache dozens of chunks safely, configure the bundler to embed a content hash—a short cryptographic fingerprint of each file's exact contents—into every chunk filename (for example,
billing.4a8c12.js):- Hashed chunk files (
*.[contenthash].js): Serve withCache-Control: public, max-age=31536000, immutable. Because any code edit produces a new filename, browsers and CDNs can cache unchanged chunks for a full year without revalidation. - HTML entry (
index.html): Serve unhashed withCache-Control: no-cache(ormax-age=0, must-revalidate) so every fresh page load checks for the latest HTML and discovers the latest chunk manifest. - Hash stability: Extract the bundler's chunk-ID-to-hash lookup table into a tiny
runtime.[contenthash].jschunk (or inline it intoindex.html) and enable deterministic module IDs (moduleIds: "deterministic"in Webpack; default in Vite/Rollup). Otherwise, editing one lazy modal changes the entry bundle's hash and invalidates every user's cache.
The hardest deployment hazard is version skew—when a user already sitting on an older tab tries to lazy-load a chunk after a new release goes live:
10:00 User opens app -> loads v1 index.html (expects billing.4a8c12.js) 10:30 Team deploys v2 -> server builds billing.9d0f51.js (and deletes v1 files!) 10:45 User clicks "/billing" -> v1 app requests billing.4a8c12.js -> HTTP 404 ChunkLoadError!Combine four layers of defense against version skew:
- Non-destructive asset retention (most important): Upload new hashed chunks alongside older ones in object storage/CDN rather than wiping the bucket, keeping old assets live for 7–30 days (while keeping backend APIs backward-compatible). Open v1 tabs continue working seamlessly.
- Controlled one-time reload on chunk error: Catch
ChunkLoadError/vite:preloadErrorand reload the page to pull v2'sindex.html, guarded bysessionStorageso a genuinely broken file never causes an infinite reload loop. - Proactive version check on navigation: Compare the running build ID against a lightweight
/version.jsonor anX-App-VersionAPI response header; if newer, turn the user's next route click into a clean full-page navigation (window.location.assign(nextUrl)). - Optional Service Worker precaching: A Service Worker (a background browser proxy script that manages a versioned local asset cache) can precache a release's chunk set atomically and activate the next version only when all tabs reload, at the cost of extra caching complexity.
import { lazy } from "react"; const RELOAD_STORAGE_KEY = "last-chunk-reload-ts"; export function lazyWithReload(importer) { return lazy(async () => { try { return await importer(); } catch (error) { const now = Date.now(); const lastReload = Number(sessionStorage.getItem(RELOAD_STORAGE_KEY) || 0); // Guard against infinite reload loops: allow at most one forced reload per 10 seconds if (now - lastReload > 10_000) { sessionStorage.setItem(RELOAD_STORAGE_KEY, String(now)); window.location.reload(); // Return a never-resolving promise while the browser unloads the page return new Promise(() => {}); } // If we already reloaded and it still fails, let the Error Boundary render Retry UI throw error; } }); }- Hashed chunk files (
4. Measure real-user impact and guard against runtime jank
Synthetic tests on a developer laptop miss slow mobile CPUs and lossy cellular links. Validate the refactor in production using Real User Monitoring (RUM)—telemetry collected from actual users' browsers in the field—evaluated at the 75th and 95th percentiles (p75 / p95) and segmented by device memory, network speed, and route.
Track both initial-load wins and post-load jank (stuttering animations or delayed tap responses caused when chunk compilation/execution blocks the main thread for more than 50 ms):
- Core Web Vitals (field p75):
- Largest Contentful Paint (LCP, target <= 2.5 s): Time until the largest visible hero image or text block renders; verifies initial splitting didn't accidentally defer above-the-fold UI.
- Interaction to Next Paint (INP, target <= 200 ms): Measures the worst-case latency from any user click, tap, or keypress across the entire session to the next painted frame. INP directly catches main-thread jank when a lazy chunk parses and executes mid-session.
- Cumulative Layout Shift (CLS, target <= 0.1): Confirms lazy components and skeletons do not shift visible content.
- Custom code-splitting telemetry:
- Route-to-route transition duration (
performance.mark/performance.measurefrom click to rendered view) at p75 and p95. - Suspense fallback rate and dwell time: How often users actually see a skeleton/spinner and for how many milliseconds.
- Chunk download failure rate per 1,000 navigations, alerted on spikes during deployments.
- Repeat-visit chunk cache hit ratio via the Resource Timing API (
transferSize === 0). - Long Animation Frames API (
long-animation-frame): Pinpoints which exact lazy chunk URL caused > 50 ms main-thread stalls during script evaluation.
- Route-to-route transition duration (
- Rollout discipline: Ship behind an A/B flag comparing bounce rate, conversion, LCP, and INP, and enforce automated CI bundle-size budgets so the initial chunk never creeps back toward 6 MB.
- Core Web Vitals (field p75):
Intuition & how it works
Shipping a 6 MB monolithic Single-Page Application (SPA)—a web app that loads one HTML shell and renders every screen in JavaScript—is like forcing a reader to haul a 20-volume encyclopedia through the door before they can read page 1 of Volume 1. Code splitting breaks that giant bundle at build time into smaller files called chunks, and lazy loading fetches extra volumes only when (or right before) the user turns to them.
The naive extremes both fail. Sending one 6 MB file upfront stalls mobile users for over 9 seconds downloading, parsing, and running code for audit logs and editors they may never open; conversely, splitting every tiny button into its own file and fetching only on click creates cascading network delays, jumping layouts, and broken tabs whenever a deployment swaps chunk filenames underneath active users.
Walk through a concrete mobile trace on a 1.5 Mbps connection (1 MB = 1,000,000 bytes):
- Before: 6 MB raw JS (~1.5 MB compressed =
12 Mbit) takes12 / 1.5 = 8.0 sjust to download, plus ~2.5 s of mobile CPU parse/execute time (~10.5 suntil interactive). - After: The entry shell + vendor bundle shrinks to 300 KB compressed (
2.4 Mbit), downloading in1.6 sand becoming interactive in~2.2 s. When the user hovers the/billinglink,<link rel="prefetch">warmsbilling.4a8c12.jsin the background (~0 msperceived wait on click), a fixed-height skeleton keeps layout shift at0.0, and keepingbilling.4a8c12.json the CDN for 7 days after deployingbilling.9d0f51.jsensures open tabs never hit a 404.
Key points
- Audit and trim before splitting: Use a bundle analyzer and DevTools Coverage to see what occupies the 6 MB, and apply tree shaking (automatically stripping unused exports at build time) and lighter dependencies before deferring bytes.
- Split routes first, heavy conditional features second: Put each URL route in its own chunk, keep the app shell and initial-screen content in the entry bundle, isolate stable framework code in a vendor chunk, and lazy-load heavy in-page widgets (spreadsheet grids, charts, maps) where
size * P(unused)is high. - Coordinate browser fetch priorities: Load the initial view eagerly, use
modulepreloadto fetch current-route sub-chunks in parallel (eliminating sequential import waterfalls), andprefetchlikely next routes on hover, viewport entry, or idle time. - Prevent layout shift and spinner flash: Match
<Suspense>skeleton dimensions (min-height/aspect-ratio) to the loaded component, keep the old screen interactive withstartTransition, and wrap lazy regions in an Error Boundary (a component that catches subtree errors and renders fallback retry UI). - Immutable chunk caching + uncached HTML: Serve content-hashed chunks (
[name].[contenthash].js) withCache-Control: public, max-age=31536000, immutable, serveindex.htmlwithCache-Control: no-cache, and isolate the bundler runtime manifest so unchanged chunks keep their hashes. - Defend against deployment version skew: Retain previous releases' hashed chunks in CDN/object storage for days, wrap dynamic imports in a loop-guarded one-time reload fallback, and check build versions on route transitions.
- Measure p75 real-user experience: Track Real User Monitoring (RUM) field telemetry for Largest Contentful Paint (LCP), Interaction to Next Paint (INP), and Cumulative Layout Shift (CLS) alongside route transition latency, Suspense dwell time, and chunk error rates.
Common mistakes
- Lazy-loading above-the-fold or hero components: Moving initial-view components out of the entry bundle forces the browser to download the entry script first and only then discover the hero chunk, making LCP slower instead of faster.
- Waiting until
clickto start fetching: Without hover/viewportprefetchormodulepreload, every first interaction pays a full mobile network round-trip plus download and compile latency. - Rendering zero-height or unmeasured
<Suspense>fallbacks: Inserting a lazy component without reserved dimensions pushes visible text down and spikes CLS if the chunk takes longer than 500 ms after a tap. - Wiping old hashed chunks from the bucket/CDN on deploy: Every user with an already-open tab immediately hits HTTP 404
ChunkLoadErroron their next navigation. - Auto-reloading on chunk failure without a loop guard: If a chunk URL is genuinely missing or blocked even after refresh, an unguarded
window.location.reload()traps the user in an infinite refresh loop. - Setting a long
max-agecache header onindex.html: Returning visitors stay pinned to a stale HTML shell that references outdated or deleted chunk hashes. - Resetting an Error Boundary around
React.lazywithout retrying the import:React.lazycaches a rejected dynamic import promise, so simply re-rendering the samelazy()component rethrows the cached error unless the retry happens inside theimport()wrapper or reloads the page.
Follow-up questions
- When multiple routes pull from a shared vendor or utility chunk, how does updating one shared dependency affect browser cache hit rates, and how do you structure shared chunks to limit invalidation? Because a chunk's content hash is computed over every byte inside it, updating even one small helper inside a shared chunk changes that chunk's filename and forces returning users to re-download the entire file. Bundling all shared dependencies into a single 800 KB
commons.jsmeans almost every deploy invalidates all 800 KB. Instead, group shared code by rate of change—for example, a ~250 KB core framework chunk (react, router) that changes a few times a year, a ~300 KB UI/design-system chunk that changes weekly, and smaller route-shared chunks—so upgrading a date helper invalidates only its small bucket while keeping the framework chunk cached. - When does aggressive code splitting start hurting performance instead of helping, and why do dozens of tiny chunks backfire? Over-splitting hurts performance when chunk granularity drops below roughly 15–20 KB compressed or creates deep dynamic-import chains. Even over HTTP/2 multiplexing (sending multiple streams over one TCP connection), each separate file adds per-request header/runtime boilerplate, compresses worse because Brotli/Gzip cannot share dictionary patterns across separate files, and under HTTP/1.1 queues behind the ~6-connection-per-origin limit. Worse, nested dynamic imports (
A -> B -> C) serialize network round-trips (3 * 150 ms = 450 msof idle waiting beforeCstarts), which is why bundlers enforce a minimum chunk threshold (splitChunks.minSize = 20000bytes in Webpack). - How can a team automate split-boundary enforcement and prefetching in CI and application code so engineers do not have to manage every dynamic import by hand? First, adopt file-system or declarative route conventions (as in Next.js, Remix, or a shared
lazyRoute()wrapper) so every new route is automatically split, prefetched on link visibility/hover, and wrapped in standard skeleton and retry boundaries with zero boilerplate. Second, configure bundlersplitChunksrules and CI bundle-budget checks that post per-chunk size diffs on pull requests and fail builds when the entry chunk exceeds its KB cap. Third, add ESLintno-restricted-importsrules banning direct static imports of heavy libraries (monaco-editor,echarts,pdfjs-dist) outside lazy wrappers, and combine RUM route-transition probabilities with Coverage telemetry to auto-tune prefetch hints toward the routes users actually visit next.
Follow-up questions
- When multiple routes pull from a shared vendor or utility chunk, how does updating one shared dependency affect browser cache hit rates, and how do you structure shared chunks to limit invalidation?
- When does aggressive code splitting start hurting performance instead of helping, and why do dozens of tiny chunks backfire?
- How can a team automate split-boundary enforcement and prefetching in CI and application code so engineers do not have to manage every dynamic import by hand?
Similar questions
- PostgreSQL Indexing, Kafka Idempotency, and Row-Lock Ordering
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager