跳转到内容

@astrojs/ partytown

这个 Astro 集成 能在你的 Astro 项目中启用 Partytown

Partytown 是一个延迟加载的库,用于帮助将资源密集型脚本转移到 Web Worker 中,从而脱离主线程

如果你正在使用第三方脚本来进行分析或投放广告,Partytown 是一个确保它们不会减慢你网站速度的好方法。

Astro Partytown 集成会为你安装 Partytown,并确保它在你所有的页面上都已启用。

Astro 包含一个 astro add 命令来自动设置官方集成。如果你愿意,也可以手动安装集成

在新的终端窗口中运行以下命令之一。

终端窗口
npx astro add partytown

如果你遇到任何问题,请随时在 GitHub 上向我们报告,并尝试下面的手动安装步骤。

首先,安装 @astrojs/partytown

终端窗口
npm install @astrojs/partytown

然后,使用 integrations 属性将此集成应用到你的 astro.config.* 文件中:

astro.config.mjs
import { defineConfig } from 'astro/config';
import partytown from '@astrojs/partytown';
export default defineConfig({
// ...
integrations: [partytown()],
});

Partytown 应该可以零配置即用。如果你网站上已有第三方脚本,请尝试添加 type="text/partytown" 属性

<script type="text/partytown" src="fancy-analytics.js"></script>

如果你从浏览器的开发者工具中打开“网络”选项卡,你应该会看到 partytown 代理正在拦截此请求。

要配置此集成,请在 astro.config.mjs 文件中将一个“config”对象传递给 partytown() 函数调用。

astro.config.mjs
export default defineConfig({
// ...
integrations: [
partytown({
config: {
// options go here
},
}),
],
});

这对应于 Partytown 的配置对象

Partytown 带有一个 debug 模式;通过向 config.debug 传递 truefalse 来启用或禁用它。如果调试模式被启用,它将在浏览器控制台中输出详细的日志。

如果未设置此选项,则 debug 模式在开发预览模式下将默认开启。

astro.config.mjs
export default defineConfig({
// ...
integrations: [
partytown({
// Example: Disable debug mode.
config: { debug: false },
}),
],
});

第三方脚本通常会将变量添加到 window 对象上,以便你可以在整个网站中与它们通信。但是,当脚本在 web-worker 中加载时,它无法访问该全局 window 对象。

为了解决这个问题,Partytown 可以将变量“修补”到全局 window 对象,并将它们转发给相应的脚本。

你可以使用 config.forward 选项指定要转发的变量。在 Partytown 的文档中阅读更多信息。

astro.config.mjs
export default defineConfig({
// ...
integrations: [
partytown({
// Example: Add dataLayer.push as a forwarding-event.
config: {
forward: ['dataLayer.push'],
},
}),
],
});

更多集成

前端框架

适配器

其他集成

贡献 社区 赞助