Skip to content
AITroveRead. Build. Understand.
Make this comfortable

HTML modulepreload: fetch a known module before its import is discovered

Last updated: 5 Oct 20266 min read
tutorial
IntermediateBy AITrove Editorial

A modulepreload link fetches a JavaScript module with module-script rules and places it in the document's module map. Ordinary preload is not an interchangeable spelling for that behavior.

Decide from the browser contract

A receipt detail route loads a module that imports a formatter used before the first interaction. When a network trace shows that dependency starts late, preloading the same deployed module path can shorten the wait. The script tag still executes the entry module; the link alone does not run code. Browsers may fetch declared dependencies as an optimization, but do not rely on a particular dependency traversal or event timing. Keep the preload list short and generated from the build output, because a renamed chunk silently turns the hint into wasted transfer. If the module is only needed after a rare click, an early fetch may compete with CSS, text, or the receipt image.

html
<head>
  <title>Receipt R-47</title>
  <link rel="modulepreload" href="/assets/receipt-format.mjs">
  <script type="module" src="/assets/receipt-view.mjs"></script>
</head>
<body>
  <main>
    <h1>Receipt R-47</h1>
    <p id="receipt-total">Total will appear after the module loads.</p>
  </main>
</body>

Cost and verification

Both module paths must exist in the deployed build, and the entry module must import the preloaded dependency at the same resolved URL for reuse. A preload moves bytes earlier; it neither reduces the module's size nor executes it. Compare a cold-load network trace and the page's meaningful render before and after adding the hint, including a slow connection. Remove it when the dependency is no longer critical. Keep the server's module MIME type, cache policy, and cross-origin rules aligned with the actual script request.

Common Mistakes

  • Do not use rel=preload with as=script and assume it populates the module map.
  • Do not preload every chunk produced by a bundler.
  • Do not leave a stale hashed filename in a hand-written template.

Connected lessons

html
browser-contract
Storage details