Skip to content
Tutorials Center
My learning

Topics

React Reference ยท react-dom Resource and Form APIs

React preinitModule() function

Reference for react-dom preinitModule(): fetch an ES module and evaluate it as soon as possible with an async module script, plus options and caveats.

preinitModule(href, options) fetches an ES module and runs it. React adds <script type="module" async src="..."> to the document head, deduplicates repeated calls, and on the server places the same tag early in the HTML stream. The module and everything it imports is evaluated as soon as it arrives.

That makes it the module version of preinit. Choose it for a self-contained module that should simply start working, such as an analytics module, a polyfill, or a custom-element definition. If you only want the bytes cached so a later import is fast, use preloadModule instead.

JSX
import { preinitModule } from 'react-dom';

preinitModule('/assets/widgets.js', { as: 'script' });

Try it

The script tag React inserts
Two components, one script

Syntax

JSX
preinitModule(href)
preinitModule(href, options)
TypeScript
function preinitModule(
  href: string,
  options?: {
    as?: 'script';
    crossOrigin?: 'anonymous' | 'use-credentials' | '';
    integrity?: string;
    nonce?: string;
  }
): void;
Name Description
href URL of the module. Must be a non-empty string.
options.as Only 'script' is valid; it is also the default. Any other value is rejected in development.
options.crossOrigin CORS mode for the request. Cross-origin modules always need CORS headers from the server.
options.integrity Subresource Integrity hash.
options.nonce Content Security Policy nonce, needed if your policy restricts scripts.

Returns: nothing (undefined).

Errors / edge cases: an empty href or an as other than 'script' logs a development error and inserts nothing.

Usage notes

  • It executes code. Only preinit modules you trust and that are safe to run before the rest of the page is ready. Because the tag is async, execution order relative to other scripts is not guaranteed.
  • Modules run once. Importing the same URL later, from your own code, reuses the already-evaluated module instance. Do not expect top-level code to run twice.
  • Dedup across calls and preloads. Many components may call it; one tag is created. A preloadModule for the same URL afterwards adds nothing.
  • Not a replacement for import. Preinit starts the module; your code still needs import or import() to use its exports. It is mostly useful for modules that act on their own, or to start the fetch earlier than your bundle's own import graph would.
  • Classic scripts (no type="module") are handled by preinit with as: 'script'.
  • Server rendering: during streaming SSR React emits the module tag in the head, so the download begins before hydration code loads.
  • Avoid it for large optional features. Prefer preloadModule plus lazy, which downloads without executing until the user needs it.