prefetchDNS 让你急切地查询你期望从中加载资源的服务器的 IP。
prefetchDNS("https://example.com");参考
🌐 Reference
prefetchDNS(href)
要查找主机,请调用 react-dom 中的 prefetchDNS 函数。
🌐 To look up a host, call the prefetchDNS function from react-dom.
import { prefetchDNS } from 'react-dom';
function AppRoot() {
prefetchDNS("https://example.com");
// ...
}prefetchDNS 函数向浏览器提供一个提示,表明它应该查找给定服务器的 IP 地址。如果浏览器选择这样做,这可以加快从该服务器加载资源的速度。
🌐 The prefetchDNS function provides the browser with a hint that it should look up the IP address of a given server. If the browser chooses to do so, this can speed up the loading of resources from that server.
参数
🌐 Parameters
href:一个字符串。你想要连接的服务器的 URL。
返回
🌐 Returns
prefetchDNS 不返回任何内容。
注意事项
🌐 Caveats
- 对同一服务器多次调用
prefetchDNS的效果与一次调用相同。 - 在浏览器中,你可以在任何情况下调用
prefetchDNS:在渲染组件时,在 Effect 中,在事件处理程序中,等等。 - 在服务端渲染或渲染服务器组件时,
prefetchDNS仅在你在渲染组件时或在源自组件渲染的异步上下文中调用时才有效。任何其他调用将被忽略。 - 如果你知道所需的具体资源,你可以改为调用 其他函数,它们将立即开始加载这些资源。
- 预取网页本身所在的同一服务器没有任何好处,因为在给出提示时它已经被查找过。
- 与
preconnect相比,如果你是投机性地连接到大量域名,prefetchDNS可能更好,在这种情况下,预连接的开销可能会超过其带来的好处。
用法
🌐 Usage
渲染时预取 DNS
🌐 Prefetching DNS when rendering
在渲染组件时,如果你知道其子组件将从该主机加载外部资源,请调用 prefetchDNS。
🌐 Call prefetchDNS when rendering a component if you know that its children will load external resources from that host.
import { prefetchDNS } from 'react-dom';
function AppRoot() {
prefetchDNS("https://example.com");
return ...;
}在事件处理程序中预取 DNS
🌐 Prefetching DNS in an event handler
在过渡到需要外部资源的页面或状态之前,在事件处理程序中调用 prefetchDNS。这样可以比在新页面或状态渲染期间调用它更早地启动进程。
🌐 Call prefetchDNS 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 { prefetchDNS } from 'react-dom';
function CallToAction() {
const onClick = () => {
prefetchDNS('http://example.com');
startWizard();
}
return (
<button onClick={onClick}>Start Wizard</button>
);
}