Preloading with Module Hints
You'll learn how to optimize dynamic imports by hinting to the browser which modules it should preload ahead of time.
The Problem: Waiting for Imports
When you use dynamic imports, the browser only starts fetching the module when it encounters the import() call. If that happens late—like after a user clicks a button—there's a delay while the module downloads. You've already learned dynamic imports themselves; now we optimize their loading.
Module Preload: A Head Start
The browser supports <link rel="modulepreload"> to tell it: "I'll need this module soon, start downloading it now." This doesn't execute the module—it just fetches and caches it so when your code later calls import(), the module is already ready.
<link rel="modulepreload" href="./heavy-chart-library.js">
Now when your code dynamically imports that module later, there's no network delay.
Webpack Magic Comments
Build tools like Webpack offer magic comments inside import() to trigger similar optimizations:
// Tell Webpack to preload this chunk
const module = await import(
/* webpackPreload: true */
'./expensive-module.js'
);
This generates preload hints in the built HTML. You can also use /* webpackPrefetch: true */ for lower-priority resources the browser fetches when idle.
When to Use This
Use module preloading when you know a module will definitely be needed soon (like on the next page or after a predictable user action). Don't preload everything—that wastes bandwidth and defeats the purpose of code splitting.
Key Takeaway: Use <link rel="modulepreload"> or bundler magic comments to fetch dynamic imports ahead of time, eliminating load delays when the module is actually needed.