preconnect

preconnect 让你能积极地连接到你期望从中加载资源的服务器。

preconnect("https://example.com");

参考

🌐 Reference

preconnect(href)

要预连接到主机,请从 react-dom 调用 preconnect 函数。

🌐 To preconnect to a host, call the preconnect function from react-dom.

import { preconnect } from 'react-dom';

function AppRoot() {
preconnect("https://example.com");
// ...
}

查看更多示例。

preconnect 函数向浏览器提供一个提示,表明它应该与给定的服务器建立连接。如果浏览器选择执行此操作,这可以加快从该服务器加载资源的速度。

🌐 The preconnect function provides the browser with a hint that it should open a connection to the given server. If the browser chooses to do so, this can speed up the loading of resources from that server.

参数

🌐 Parameters

  • href:一个字符串。你想要连接的服务器的 URL。

返回

🌐 Returns

preconnect 不返回任何内容。

注意事项

🌐 Caveats

  • 对同一服务器多次调用 preconnect 的效果与一次调用相同。
  • 在浏览器中,你可以在任何情况下调用 preconnect:在渲染组件时,在 Effect 中,在事件处理程序中,等等。
  • 在服务端渲染或渲染服务器组件时,preconnect 仅在你在渲染组件时或在源自组件渲染的异步上下文中调用时才有效。任何其他调用将被忽略。
  • 如果你知道所需的具体资源,你可以改为调用 其他函数,它们将立即开始加载这些资源。
  • 预连接到托管网页本身的同一服务器没有任何好处,因为在给出提示时它已经被连接到。

用法

🌐 Usage

渲染时预连接

🌐 Preconnecting when rendering

在渲染组件时,如果你知道它的子组件将从该主机加载外部资源,请调用 preconnect

🌐 Call preconnect when rendering a component if you know that its children will load external resources from that host.

import { preconnect } from 'react-dom';

function AppRoot() {
preconnect("https://example.com");
return ...;
}

在事件处理程序中预连接

🌐 Preconnecting in an event handler

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

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

function CallToAction() {
const onClick = () => {
preconnect('http://example.com');
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}