注意

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

preload 让你积极地获取你预计会使用的资源,例如样式表、字体或外部脚本。

preload("https://example.com/font.woff2", {as: "font"});

参考

🌐 Reference

preload(href, options)

要预加载资源,请调用 react-dom 中的 preload 函数。

🌐 To preload a resource, call the preload function from react-dom.

import { preload } from 'react-dom';

function AppRoot() {
preload("https://example.com/font.woff2", {as: "font"});
// ...
}

查看更多示例。

preload 函数向浏览器提供一个提示,它应开始下载给定的资源,这可以节省时间。

🌐 The preload function provides the browser with a hint that it should start downloading the given resource, which can save time.

参数

🌐 Parameters

  • href:一个字符串。你想下载的资源的 URL。
  • options:一个对象。它包含以下属性:
    • as:必填字符串。资源的类型。它的可能值audiodocumentembedfetchfontimageobjectscriptstyletrackvideoworker
    • crossOrigin:一个字符串。要使用的 CORS 策略。其可能的值为 anonymoususe-credentials。当 as 设置为 "fetch" 时,此项为必填项。
    • referrerPolicy:一个字符串。获取时要发送的 Referrer header。它的可能值是 no-referrer-when-downgrade(默认值)、no-referreroriginorigin-when-cross-originunsafe-url
    • integrity:一个字符串。资源的加密哈希,用于验证其真实性
    • type:一个字符串。资源的 MIME 类型。
    • nonce:一个字符串。在使用严格的内容安全策略时,允许资源的加密随机数
    • fetchPriority:一个字符串。表示获取资源的相对优先级。可能的值为 auto(默认)、highlow
    • imageSrcSet:一个字符串。仅用于 as: "image"。指定图片的源集合
    • imageSizes:一个字符串。仅用于 as: "image"。指定图片的大小

返回

🌐 Returns

preload 不返回任何内容。

注意事项

🌐 Caveats

  • preload 的多次等效调用与一次调用效果相同。根据以下规则,preload 的调用被视为等效:
    • 如果两个调用的 href 相同,则它们是等价的,但以下情况除外:
    • 如果 as 设置为 image,当两次调用具有相同的 hrefimageSrcSetimageSizes 时,它们是等价的。
  • 在浏览器中,你可以在任何情况下调用 preload:在渲染组件时,在 Effect 中,在事件处理程序中,等等。
  • 在服务端渲染或渲染服务器组件时,preload 仅在你在渲染组件时或在源自组件渲染的异步上下文中调用时才有效。任何其他调用将被忽略。

用法

🌐 Usage

渲染时预加载

🌐 Preloading when rendering

在渲染组件时调用 preload,如果你知道它或它的子组件将使用特定资源。

🌐 Call preload when rendering a component if you know that it or its children will use a specific resource.

Examples of preloading

例子 1 of 4:
预加载外部脚本

🌐 Preloading an external script

import { preload } from 'react-dom';

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

如果你希望浏览器立即开始执行脚本(而不仅仅是下载它),请使用 preinit。如果你想加载一个 ESM 模块,请使用 preloadModule

🌐 If you want the browser to start executing the script immediately (rather than just downloading it), use preinit instead. If you want to load an ESM module, use preloadModule.

在事件处理程序中预加载

🌐 Preloading in an event handler

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

🌐 Call preload 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 { preload } from 'react-dom';

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