preinitModule

注意

基于 React 的框架 通常会为你处理资源加载,因此你可能不需要自己调用这个 API。有关详细信息,请查阅你使用的框架文档。

preinitModule 让你能够急切地获取并评估一个 ESM 模块。

preinitModule("https://example.com/module.js", {as: "script"});

参考

🌐 Reference

preinitModule(href, options)

要预初始化一个 ESM 模块,请调用来自 react-dompreinitModule 函数。

🌐 To preinit an ESM module, call the preinitModule function from react-dom.

import { preinitModule } from 'react-dom';

function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
// ...
}

查看更多示例。

preinitModule 函数向浏览器提供了一个提示,告诉它应该开始下载并执行给定的模块,这可以节省时间。你 preinit 的模块会在下载完成后执行。

🌐 The preinitModule function provides the browser with a hint that it should start downloading and executing the given module, which can save time. Modules that you preinit are executed when they finish downloading.

参数

🌐 Parameters

  • href:一个字符串。你想要下载并执行的模块的 URL。
  • options:一个对象。它包含以下属性:
    • as:一个必需的字符串。它必须是 'script'
    • crossOrigin:一个字符串。要使用的 CORS 策略。它的可能值是 anonymoususe-credentials
    • integrity:一个字符串。模块的加密哈希,用于验证其真实性
    • nonce:一个字符串。一个加密 nonce,以允许模块 在使用严格的内容安全策略时。

返回

🌐 Returns

preinitModule 不返回任何内容。

注意事项

🌐 Caveats

  • 多次使用相同的 href 调用 preinitModule 与一次调用的效果相同。
  • 在浏览器中,你可以在任何情况下调用 preinitModule:在渲染组件时,在 Effect 中,在事件处理程序中,等等。
  • 在服务端渲染或渲染服务器组件时,preinitModule 仅在你在渲染组件时或在源自组件渲染的异步上下文中调用它时才会生效。任何其他调用都会被忽略。

用法

🌐 Usage

渲染时预加载

🌐 Preloading when rendering

在渲染组件时调用 preinitModule,如果你知道它或者它的子组件将使用特定模块,并且你可以接受该模块在被下载后立即被评估从而生效。

🌐 Call preinitModule when rendering a component if you know that it or its children will use a specific module and you’re OK with the module being evaluated and thereby taking effect immediately upon being downloaded.

import { preinitModule } from 'react-dom';

function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
return ...;
}

如果你希望浏览器下载模块但不是立即执行它,请使用 preloadModule。如果你想预初始化不是 ESM 模块的脚本,请使用 preinit

🌐 If you want the browser to download the module but not to execute it right away, use preloadModule instead. If you want to preinit a script that isn’t an ESM module, use preinit.

在事件处理程序中预加载

🌐 Preloading in an event handler

在过渡到需要该模块的页面或状态之前,在事件处理程序中调用 preinitModule。这比在新页面或状态渲染期间调用它更早地启动该过程。

🌐 Call preinitModule in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state.

import { preinitModule } from 'react-dom';

function CallToAction() {
const onClick = () => {
preinitModule("https://example.com/module.js", {as: "script"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}