preinitModule 允许您提前获取并评估一个 ESM 模块。
preinitModule("https://example.com/module.js", {as: "script"});参考
preinitModule(href, options)
要预初始化一个 ESM 模块,请从 react-dom 调用 preinitModule 函数。
import { preinitModule } from 'react-dom';
function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
// ...
}preinitModule 函数向浏览器提供一个提示,指示它应该开始下载并执行给定的模块,这可以节省时间。 您 preinit 的模块将在下载完成后执行。
参数
href:字符串。您想要下载并执行的模块的 URL。options:对象。它包含以下属性as:必需字符串。它必须是'script'。crossOrigin:字符串。CORS策略。它的可能值是anonymous和use-credentials。integrity:字符串。模块的加密哈希,用于验证其真实性。nonce:字符串。一个加密nonce,在使用严格的内容安全策略时允许模块。
返回值
preinitModule 不返回任何值。
注意事项
- 多次使用相同
href值调用preinitModule与单次调用效果相同。 - 在浏览器中,你可以在任何情况下调用
preinitModule:组件渲染期间、Effect 中、事件处理程序中等等。 - 在服务器端渲染或渲染服务器组件时,只有在组件渲染期间或来自组件渲染的异步上下文中调用
preinitModule才会生效。其他任何调用都会被忽略。
使用方法
渲染时的预加载
如果你知道组件或其子组件将使用特定模块,并且你同意该模块在下载后立即被评估并生效,则在渲染组件时调用preinitModule。
import { preinitModule } from 'react-dom';
function AppRoot() {
preinitModule("https://example.com/module.js", {as: "script"});
return ...;
}如果你希望浏览器下载模块但不立即执行它,请改用preloadModule。如果你想预初始化一个不是ESM模块的脚本,请使用preinit。
事件处理程序中的预加载
在切换到需要该模块的页面或状态之前,在事件处理程序中调用preinitModule。这使得该过程比在新页面或状态渲染期间调用它开始得更早。
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>
);
}