Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,28 @@ export default {

Here are the available options:

| Name | Type | Description | Defaults |
| ------ | --------- | ---------------------------------- | ----------- |
| id | `string` | Google tag ID | `undefined` |
| enable | `boolean` | Whether to enable Google Analytics | `true` |
| Name | Type | Description | Defaults |
| ------------- | -------------------- | --------------------------------------------------- | ----------- |
| id | `string` | Google tag ID | `undefined` |
| enable | `boolean` | Whether to enable Google Analytics | `true` |
| scriptLoading | `'async' \| 'defer'` | Loading strategy for the external Google tag script | `'async'` |

### scriptLoading

The default `async` matches [Google's setup example](https://developers.google.com/tag-platform/gtagjs#add_the_google_tag_to_your_website) and executes the external script as soon as it is available.

Set `scriptLoading` to `defer` to execute the external script after HTML parsing, in document order with other deferred scripts:

```ts
pluginGoogleAnalytics({
id: 'G-xxxxxxxxxx',
scriptLoading: 'defer',
});
```

This option only affects the external script. The inline `dataLayer` and `gtag` initialization still runs immediately so events can be queued before the external script loads.

A deferred script delays `DOMContentLoaded` and can delay other deferred scripts placed after it. It does not guarantee execution after application hydration.

## TypeScript support

Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,17 @@ export type PluginGoogleAnalyticsOptions = {
* @default true
*/
enable?: boolean;
/**
* Loading strategy for the external Google tag script.
* @default 'async'
*/
scriptLoading?: 'async' | 'defer';
};

export const pluginGoogleAnalytics = ({
id,
enable = true,
scriptLoading = 'async',
}: PluginGoogleAnalyticsOptions): RsbuildPlugin => ({
name: 'rsbuild-plugin-google-analytics',

Expand All @@ -36,7 +42,7 @@ export const pluginGoogleAnalytics = ({
{
tag: 'script',
attrs: {
async: true,
[scriptLoading]: true,
src: `https://www.googletagmanager.com/gtag/js?id=${id}`,
},
},
Expand Down
Loading