注意

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

preinit 让你急切地获取并评估样式表或外部脚本。

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

参考

🌐 Reference

preinit(href, options)

要预初始化脚本或样式表,请从 react-dom 调用 preinit 函数。

🌐 To preinit a script or stylesheet, call the preinit function from react-dom.

import { preinit } from 'react-dom';

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

查看更多示例。

preinit 函数向浏览器提供一个提示,告诉它应该开始下载并执行给定的资源,这可以节省时间。你 preinit 的脚本在下载完成后会被执行。你预初始化的样式表会被插入到文档中,这会使它们立即生效。

🌐 The preinit function provides the browser with a hint that it should start downloading and executing the given resource, which can save time. Scripts that you preinit are executed when they finish downloading. Stylesheets that you preinit are inserted into the document, which causes them to go into effect right away.

参数

🌐 Parameters

  • href:一个字符串。你想要下载并执行的资源的 URL。
  • options:一个对象。它包含以下属性:
    • as:必需的字符串。资源的类型。它的可能值是 scriptstyle
    • precedence:一个字符串。样式表是必需的。用于说明相对于其他样式表的位置插入样式表。具有更高优先级的样式表可以覆盖优先级较低的样式表。可能的值是 resetlowmediumhigh
    • crossOrigin:一个字符串。要使用的 CORS 策略。它的可能值是 anonymoususe-credentials
    • integrity:一个字符串。资源的加密哈希,用于验证其真实性
    • nonce:一个字符串。在使用严格的内容安全策略时,允许资源的加密随机数
    • fetchPriority:一个字符串。表示获取资源的相对优先级。可能的值为 auto(默认)、highlow

返回

🌐 Returns

preinit 不返回任何内容。

注意事项

🌐 Caveats

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

用法

🌐 Usage

渲染时预初始化

🌐 Preiniting when rendering

在渲染组件时调用 preinit,如果你知道它或它的子组件将使用某个特定资源,并且你可以接受该资源在下载后立即被评估并生效。

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

Examples of preiniting

例子 1 of 2:
预初始化外部脚本

🌐 Preiniting an external script

import { preinit } from 'react-dom';

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

如果你希望浏览器下载脚本但不立即执行,请使用 preload。如果你想加载一个 ESM 模块,请使用 preinitModule

🌐 If you want the browser to download the script but not to execute it right away, use preload instead. If you want to load an ESM module, use preinitModule.

在事件处理程序中预初始化

🌐 Preiniting in an event handler

在过渡到需要外部资源的页面或状态之前,在事件处理程序中调用 preinit。这样可以比在新页面或状态渲染期间调用它更早地启动进程。

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

import { preinit } from 'react-dom';

function CallToAction() {
const onClick = () => {
preinit("https://example.com/wizardStyles.css", {as: "style"});
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}