Partytown
Guidelines for using the @astrojs/partytown integration to offload third-party scripts.
astro
## Astro Partytown Integration Guidelines
1. Purpose: Moves resource-intensive third-party scripts (like analytics, ads, tag managers) off the main browser thread and into a web worker. This improves site performance and responsiveness by preventing these scripts from blocking the main thread.
2. Installation: Install using the Astro CLI:
```bash
npx astro add partytown
# or pnpm add @astrojs/partytown / yarn add @astrojs/partytown
```
This installs the package and adds it to your `astro.config.mjs`.
3. Usage:
- After installation, identify third-party `<script>` tags in your project (usually in layouts or specific pages).
- Change the `type` attribute of these scripts from `text/javascript` (or omit it) to `type="text/partytown"`.
```html
<!-- Before -->
<script src="https://example.com/analytics.js"></script>
<!-- After -->
<script
type="text/partytown"
src="https://example.com/analytics.js"
></script>
```
- Partytown will intercept requests for scripts with this type and run them in the web worker.
4. Configuration (Optional): Pass a `config` object to the `partytown()` integration in `astro.config.mjs`.
```javascript
// astro.config.mjs
import { defineConfig } from "astro/config";
import partytown from "@astrojs/partytown";
export default defineConfig({
integrations: [
partytown({
// Partytown config options go here
config: {
debug: false, // Example: Disable debug logs
forward: ["dataLayer.push"], // Example: Forward events
},
}),
],
});
```
- `config.debug`: `boolean` - Enables/disables Partytown's detailed console logging. Defaults to `true` in dev/preview, `false` in production.
- `config.forward`: `string[]` - An array of global variables/functions (as strings) that need to be forwarded from the main thread to the web worker (e.g., `['dataLayer.push']` for Google Tag Manager). Necessary for communication with scripts running in the worker.
5. Verification: After adding `type="text/partytown"`, use your browser's developer tools (Network tab) to check if requests for these scripts are being handled by the `partytown` proxy.
Reference: [@astrojs/partytown Integration Docs](https://docs.astro.build/en/guides/integrations-guide/partytown/)