The modulepreload
keyword, for the rel
attribute of the <link>
element, provides a declarative way to preemptively fetch a module script, parse and compile it, and store it in the document's module map for later execution.
Preloading allows modules and their dependencies to be downloaded early, and can also significantly reduce the overall download and processing time. This is because it allows pages to fetch modules in parallel, instead of sequentially as each module is processed and its dependencies are discovered. Note however that you can't just preload everything! What you choose to preload must be balanced against other operations that might then be starved, adversely affecting user experience.
Links with rel="modulepreload"
are similar to those with rel="preload"
. The main difference is that preload
just downloads the file and stores it in the cache, while modulepreload
gets the module, parses and compiles it, and puts the results into the module map so that it is ready to execute.
When using modulepreload
the fetch request mode is always cors
, and the crossorigin
property is used to determine the request credential mode. If crossorigin
is set to anonymous
or ""
(default), then the credentials mode is same-origin
, and user credentials such as cookies and authentication are only sent for requests with the same-origin
. If crossorigin
is set to use-credentials
then the credentials mode is include
, and user credentials for both single- and cross-origin requests.
The as
attribute is optional for links with rel="modulepreload"
, and defaults to "script"
. It can be set to "script"
or any script-like destination, such as "audioworklet"
, "paintworklet"
, "serviceworker"
, "sharedworker"
, or "worker"
. An Event
named "error" is fired on the element if any other destination is used.
A browser may additionally also choose to automatically fetch any dependencies of the module resource. Note however that this is a browser-specific optimization — the only approach to ensure that all browsers will try to preload a module's dependencies is to individually specify them! Further, the events named load
or error
fire immediately following success or failure of loading the specified resources. If dependencies are automatically fetched, no additional events are fired in the main thread (although you might monitor additional requests in a service worker or on the server).