Prefetching and Preloading Chunks
What you'll learn: How to use magic comments in dynamic imports to control when and how split code chunks are loaded.
The Power of Hints
You've learned to split your code into chunks with dynamic imports, but sometimes you want to be proactive about loading those chunks. Instead of waiting until a user clicks a button, what if you could tell the browser: "Hey, load this chunk during idle time—I think we'll need it soon"?
That's where magic comments come in. These special comments inside your import() statements give the bundler hints about loading priorities.
The Two Strategies
Prefetch tells the browser to download a chunk during idle time, after the current page finishes loading. It's like saying "grab this when you're not busy—we'll probably need it later":
// Load the admin panel when browser is idle
const loadAdmin = () => import(/* webpackPrefetch: true */ './AdminPanel.js');
Preload tells the browser to download a chunk in parallel with the parent chunk, at medium priority. It's for resources you know you'll need very soon:
// Load critical authentication module immediately
const loadAuth = () => import(/* webpackPreload: true */ './Auth.js');
Think of prefetch as "stock the warehouse during downtime" and preload as "bring this to the counter right now—customer is checking out."
When to Use Each
Use prefetch for likely next steps (next page in a wizard, settings panel). Use preload sparingly for truly critical resources needed milliseconds after load. Overusing preload can actually hurt performance by competing with essential resources.
Most bundlers (Webpack, Vite with plugins) respect these comments and generate the appropriate <link rel="prefetch"> or <link rel="preload"> tags.
Key Takeaway: Magic comments like webpackPrefetch and webpackPreload let you optimize chunk loading by hinting when the browser should fetch split code—either during idle time or immediately alongside critical resources.