Dynamic Imports and Prefetching Strategies
Dynamic Imports and Prefetching Strategies
Code splitting saves bandwidth on initial load, but naive splitting introduces navigation latency: when a user clicks a route or modal button, they must pause while the browser makes a round-trip network request to fetch the JavaScript chunk. Prefetching strategies bridge this gap by intelligently downloading code chunks ahead of user interaction.
1. The Latency Gap of Lazy Loading
Consider this user timeline without prefetching:
- 1User hovers over "Analytics" link (0ms).
- 2User clicks "Analytics" link (300ms).
- 3Browser initiates network request for
analytics.chunk.js(305ms). - 4Network roundtrip and bundle execution takes 400ms.
- 5User stares at a loading spinner until 705ms.
With Hover/Intent Prefetching, the chunk starts downloading at 0ms. By 300ms, the chunk is already cached in browser memory, rendering the view immediately on click.
2. Programmatic Dynamic Prefetching
Because dynamic import() returns a standard JavaScript Promise, you can trigger chunk evaluation on standard DOM events:
3. Webpack & Rollup Magic Comments
Modern bundlers support declarative prefetching annotations embedded inside dynamic import() statements:
Webpack Magic Comments
webpackPrefetch: true: Injects<link rel="prefetch" href="admin-report.chunk.js">into the document<head>, downloading the chunk during browser idle time after the parent page finishes loading.webpackPreload: true: Injects<link rel="preload">, instructing the browser to download the chunk with high priority alongside the parent page.
4. Viewport Intersection Prefetching
For bottom-of-page sections or long infinite feeds, prefetch chunks when a scroll anchor enters the viewport using IntersectionObserver:
5. Network-Aware Prefetching
Never waste cellular mobile data. Use navigator.connection to disable aggressive prefetching on slow connections or when Data Saver mode is enabled:
Practice Quiz
Analyzing Bundle Sizes with Rollup and Webpack Visualizer
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Component-Level Lazy Loading with Suspense | Analyzing Bundle Sizes with Rollup and Webpack Visualizer |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.