The <link rel="preload"></link> HTML feature can be used to fetch scripts and static data on document load, but it doesn't seem to have any provisions for Javascript modules at all.
developer.mozilla.org
A recent <link rel="modulepreload"></link> feature has been advertised by Google as solving this, while they also explicitly explained why rel="preload" wouldn't work for modules:
developers.google.com
Support for this feature in Firefox is unclear, but it is apparently part of the WHATWG HTML Standard:
caniuse.com github.com
developer.mozilla.org html.spec.whatwg.org
Can <link rel="modulepreload></link> be used for modules dynamically imported with calls to import(modulepath)? Is this use supported both in practice and by the relevant specifications, and if not, then what is the best way to preload dynamically imported Javascript modules?
Yes, rel="modulepreload" should also work for dynamic import() calls in Javascript. It should put the fetched modules in the JS module map that's used for all static and dynamic imports.
If you'd read the spec you'd linked, you'd have noticed that it specifically gives this case as an example:
The following code shows how
modulepreloadlinks can be used in conjunction withimport()to ensure network fetching is done ahead of time, so that whenimport()is called, the module is already ready (but not evaluated) in the module map:<link rel="modulepreload" href="awesome-viewer.mjs"> <button onclick="import('./awesome-viewer.mjs').then(m => m.view())"> View awesome thing </button>
https://html.spec.whatwg.org/multipage/links.html#example-modulepreload-dynamic-import
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With