Modulepreload for ES Modules
You'll learn how to use modulepreload to speed up ES module loading by preloading modules and their dependency trees before they're needed.
What is Modulepreload?
When you use ES modules with import statements, the browser discovers dependencies one by one as it parses each file. Module A imports Module B, which imports Module C—each discovery adds network round-trip latency. The modulepreload resource hint tells the browser to fetch and compile an ES module and all its dependencies ahead of time, so when your code actually executes the import, everything is already loaded.
Think of it like pre-ordering ingredients for a recipe. Instead of sending someone to the store for flour, then discovering you need eggs and sending them again, you give them the complete shopping list upfront—one trip, everything ready.
How to Use Modulepreload
Add a <link> tag in your HTML <head>:
<link rel="modulepreload" href="/js/main.js">
<link rel="modulepreload" href="/js/utils.js">
The browser will:
- Fetch these modules with high priority
- Parse and compile them into the module cache
- Recursively fetch their dependencies
- Have everything ready when your actual
<script type="module">runs
When to Use It
Use modulepreload for:
- Your application's entry point module
- Critical modules needed for initial render
- Large modules with deep dependency trees
Don't overuse it—only preload modules you know will execute soon. Unlike preload, modulepreload understands module semantics and dependency graphs.
Key Takeaway: modulepreload eliminates module discovery latency by telling the browser to fetch and compile ES modules and their dependencies upfront, making module execution nearly instantaneous when needed.