Skip to content

预取

页面加载时间对于网站的可用性和整体享受起着重要作用。Astro 的选择加入预取功能为你的多页应用 (MPA) 带来了近乎即时的页面导航优势,因为你的访问者与网站交互。

¥Page load times play a big role in the usability and overall enjoyment of a site. Astro’s opt-in prefetching brings the benefits of near-instant page navigations to your multi-page application (MPA) as your visitors interact with the site.

¥Enable prefetching

你可以使用 prefetch 配置启用预取:

¥You can enable prefetching with the prefetch config:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
prefetch: true
});

预取脚本将添加到你网站的所有页面。然后,你可以将 data-astro-prefetch 属性添加到网站上的任何 <a /> 链接以选择预取。当你将鼠标悬停在链接上时,脚本将在后台获取页面。

¥A prefetch script will be added to all pages of your site. You can then add the data-astro-prefetch attribute to any <a /> links on your site to opt-in to prefetching. When you hover over the link, the script will fetch the page in the background.

<a href="/about" data-astro-prefetch>

请注意,预取仅适用于站点内的链接,不适用于外部链接。

¥Note that prefetching only works for links within your site, and not external links.

¥Prefetch configuration

prefetch 配置还接受选项对象以进一步自定义预取。

¥The prefetch config also accepts an option object to further customize prefetching.

¥Prefetch strategies

Astro 支持 4 种预取策略,适用于各种用例:

¥Astro supports 4 prefetch strategies for various use cases:

  • hover(默认):当你将鼠标悬停在链接上或将焦点放在链接上时预取。

  • tap:在单击链接之前预取。

  • viewport:当链接进入视口时预取。

  • load:页面加载后预取页面上的所有链接。

你可以通过将单个链接传递给 data-astro-prefetch 属性来指定该策略:

¥You can specify a strategy for an individual link by passing it to the data-astro-prefetch attribute:

<a href="/about" data-astro-prefetch="tap">About</a>

每个策略都经过微调,仅在需要时预取并节省用户的带宽。例如:

¥Each strategy is fine-tuned to only prefetch when needed and save your users’ bandwidth. For example:

¥Default prefetch strategy

添加 data-astro-prefetch 属性时默认的预取策略是 hover。要更改它,你可以在 astro.config.mjs 文件中配置 prefetch.defaultStrategy

¥The default prefetch strategy when adding the data-astro-prefetch attribute is hover. To change it, you can configure prefetch.defaultStrategy in your astro.config.mjs file:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
prefetch: {
defaultStrategy: 'viewport'
}
});

¥Prefetch all links by default

如果要预取所有链接,包括那些没有 data-astro-prefetch 属性的链接,可以将 prefetch.prefetchAll 设置为 true

¥If you want to prefetch all links, including those without the data-astro-prefetch attribute, you can set prefetch.prefetchAll to true:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
prefetch: {
prefetchAll: true
}
});

然后,你可以通过设置 data-astro-prefetch="false" 来选择不预取各个链接:

¥You can then opt-out of prefetching for individual links by setting data-astro-prefetch="false":

<a href="/about" data-astro-prefetch="false">About</a>

所有链接的默认预取策略都可以使用 prefetch.defaultStrategy 进行更改,如 默认预取策略部分 中所示。

¥The default prefetch strategy for all links can be changed with prefetch.defaultStrategy as shown in the Default prefetch strategy section.

¥Prefetch programmatically

由于某些导航可能并不总是显示为 <a /> 链接,你还可以使用 astro:prefetch 模块中的 prefetch() API 以编程方式预取:

¥As some navigation might not always appear as <a /> links, you can also prefetch programmatically with the prefetch() API from the astro:prefetch module:

<button id="btn">Click me</button>
<script>
import { prefetch } from 'astro:prefetch';
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
prefetch('/about');
});
</script>

prefetch() API 包括相同的 数据保护模式连接缓慢 检测,因此它仅在需要时预取。

¥The prefetch() API includes the same data saver mode and slow connection detection so that it only prefetches when needed.

要忽略慢速连接检测,可以使用 ignoreSlowConnection 选项:

¥To ignore slow connection detection, you can use the ignoreSlowConnection option:

// Prefetch even on data saver mode or slow connection
prefetch('/about', { ignoreSlowConnection: true });

确保仅在客户端脚本中导入 prefetch(),因为它依赖于浏览器 API。

¥Make sure to only import prefetch() in client-side scripts as it relies on browser APIs.

与视图转换一起使用

标题部分 与视图转换一起使用

¥Using with View Transitions

当你在页面上使用 查看转场 时,预取也会默认启用。它设置默认配置 { prefetchAll: true },从而在页面上启用 预取所有链接

¥When you use View Transitions on a page, prefetching will also be enabled by default. It sets a default configuration of { prefetchAll: true } which enables prefetching for all links on the page.

你可以自定义 astro.config.mjs 中的预取配置以覆盖默认值。例如:

¥You can customize the prefetch configuration in astro.config.mjs to override the default. For example:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
// Disable prefetch completely
prefetch: false
});
astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
// Keep prefetch, but only prefetch for links with `data-astro-prefetch`
prefetch: {
prefetchAll: false
}
});

¥Browser support

如果浏览器支持,Astro 的预取功能将使用 <link rel="prefetch">,否则将回退到 fetch() API

¥Astro’s prefetching uses <link rel="prefetch"> if supported by the browser, and falls back to the fetch() API otherwise.

最常见的浏览器支持 Astro 的预取,但有细微的差别:

¥The most common browsers support Astro’s prefetching with subtle differences:

Chrome 支持 <link rel="prefetch">。预取按预期工作。

¥Chrome supports <link rel="prefetch">. Prefetching works as intended.

Firefox 支持 <link rel="prefetch">,但可能会显示错误或完全失败:

¥Firefox supports <link rel="prefetch"> but may display errors or fail entirely:

  • 如果没有显式缓存标头(例如 Cache-ControlExpires),预取将因 NS_BINDING_ABORTED 而出错。

  • 即使发生错误,如果响应具有正确的 ETag 标头,它也将在导航中重新使用。

  • 否则,如果没有其他缓存标头而出错,则预取将不起作用。

Safari 不支持 <link rel="prefetch">,将回退到需要设置缓存标头(例如 Cache-ControlExpiresETag)的 fetch() API。否则,预取将不起作用。

¥Safari does not support <link rel="prefetch"> and will fall back to the fetch() API which requires cache headers (e.g. Cache-Control, Expires, and ETag) to be set. Otherwise, the prefetch will not work.

边缘情况:ETag 标题在私有窗口中不起作用。

¥Edge case: ETag headers do not work in private windows.

¥Recommendations

为了最好地支持所有浏览器,请确保你的页面具有正确的缓存标头。

¥To best support all browsers, make sure your pages have the proper cache headers.

对于静态或预渲染页面,ETag 标头通常由部署平台自动设置,并且预计开箱即用。

¥For static or prerendered pages, the ETag header is often automatically set by the deployment platform and is expected to work out of the box.

对于动态和服务器端渲染的页面,请根据页面内容自行设置适当的缓存标头。访问 有关 HTTP 缓存的 MDN 文档 了解更多信息。

¥For dynamic and server-side rendered pages, set the appropriate cache headers yourself based on the page content. Visit the MDN documentation on HTTP caching for more information.

@astrojs/prefetch 迁移

标题部分 从 @astrojs/prefetch 迁移

¥Migrating from @astrojs/prefetch

@astrojs/prefetch 集成在 v3.5.0 中已弃用,最终将被完全删除。使用以下说明迁移到 Astro 的内置预取,以取代此集成。

¥The @astrojs/prefetch integration was deprecated in v3.5.0 and will eventually be removed entirely. Use the following instructions to migrate to Astro’s built-in prefetching which replaces this integration.

  1. Remove the @astrojs/prefetch integration and enable the prefetch config in astro.config.mjs:

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import prefetch from '@astrojs/prefetch';
    export default defineConfig({
    integrations: [prefetch()],
    prefetch: true
    });
  2. Convert from @astrojs/prefetch’s configuration options:

    • The deprecated integration used the selector config option to specify which links should be prefetched upon entering the viewport.

      Add data-astro-prefetch="viewport" to these individual links instead.

      <a href="/about" data-astro-prefetch="viewport">
    • The deprecated integration used the intentSelector config option to specify which links should be prefetched when they were hovered over or focused.

      Add data-astro-prefetch or data-astro-prefetch="hover" to these individual links instead:

      <!-- You can omit the value if `defaultStrategy` is set to `hover` (default) -->
      <a href="/about" data-astro-prefetch>
      <!-- Otherwise, you can explicitly define the prefetch strategy -->
      <a href="/about" data-astro-prefetch="hover">
    • The throttles option from @astrojs/prefetch is no longer needed as the new prefetch feature will automatically schedule and prefetch optimally.

Astro 中文网 - 粤ICP备13048890号