Web performance often comes down to smart resource loading. While we’ve had preload hints for a while, modulepreload is specifically designed for the way modern JavaScript works. Let’s unpack what makes it special.
Update: One modulepreload doesn’t fetch the whole graph
I originally wrote that a single modulepreload fetches a module’s entire dependency graph. It doesn’t.
The HTML spec lets browsers fetch a preloaded module’s dependencies only as an optional optimization. MDN says the only way to make every browser preload them is to list each module (HTML spec, MDN). I’ve fixed the paragraph and the example below.
<link rel="modulepreload">
Baseline Widely available
Supported in Chrome: yes.
Supported in Edge: yes.
Supported in Firefox: yes.
Supported in Safari: yes.
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2023
When you use <link rel="modulepreload">, you’re telling the browser: “Hey, I’m going to need this module soon - could you fetch it and get it ready?” The browser then fetches the module, parses it, and compiles it ahead of time. This is different from regular preload, which only handles the fetching part.
<!-- This only fetches the file --><link rel="preload" href="/js/app.js" as="script">
<!-- This fetches, parses, and compiles the module --><link rel="modulepreload" href="/js/app.js">The real power comes when dealing with module dependencies. Without hints, the browser only finds out that main.js imports utils.js and data.js after it has fetched and parsed main.js, so the modules load one after another.
A modulepreload for each module lets the browser fetch them in parallel and put them straight into its module map. Browsers may also fetch a preloaded module’s dependencies on their own, but that’s optional, so list every module you need early.
<!-- Before: Multiple preloads needed --><link rel="preload" href="/js/main.js" as="script"><link rel="preload" href="/js/utils.js" as="script"><link rel="preload" href="/js/data.js" as="script">
<!-- After: one modulepreload per module --><link rel="modulepreload" href="/js/main.js"><link rel="modulepreload" href="/js/utils.js"><link rel="modulepreload" href="/js/data.js">When to use modulepreload
modulepreload excels in applications with substantial JavaScript dependencies or route-based code splitting. But consider the memory trade-off - modulepreload compiles modules upfront, consuming more memory. For smaller apps or rarely-used modules, regular dynamic imports might be more efficient.
