hypnagaga/src/components/Analytics/Analytics.mdx
2025-02-07 12:48:42 +00:00

73 lines
2 KiB
Text

import { Meta } from '@storybook/blocks';
import * as AnalyticsStories from './Analytics.stories.svelte';
<Meta of={AnalyticsStories} />
# Analytics
Add Google and Chartbeat analytics to your page.
```svelte
<script>
import { Analytics } from '@reuters-graphics/graphics-components';
const authors = [{ name: 'Jane Doe' }, { name: 'John Doe' }];
</script>
<Analytics {authors} />
```
## Environments
Generally, you only want to send page analytics in production environments.
In a SvelteKit context, you can use `$app` stores to restrict when you send analytics.
For example, the following excludes analytics from pages in development or hosted on our preview server:
```svelte
<script>
import { Analytics } from '@reuters-graphics/graphics-components';
import { dev } from '$app/environment';
import { page } from '$app/stores';
</script>
{#if !dev && $page.url?.hostname !== 'graphics.thomsonreuters.com'}
<Analytics />
{/if}
```
## Multipage apps
If you're using analytics to measure a multipage newsapp that uses [client-side routing](https://kit.svelte.dev/docs/glossary#routing), then you may need to trigger analytics after virtual page navigation.
This component also exports a function you can call to register pageviews.
For example, here's how you can use SvelteKit's [`afterNavigate`](https://kit.svelte.dev/docs/modules#$app-navigation-afternavigate) lifecycle to capture additional pageviews:
```svelte
<script>
import {
Analytics,
registerPageview,
} from '@reuters-graphics/graphics-components';
import { afterNavigate } from '$app/navigation';
let isFirstPageview = true;
afterNavigate(() => {
// We shouldn't fire on initial page load because the Analytics component
// already registers a reader's first pageview. After this component
// has initially mounted, we can be sure that further navigation is virtual
// and register pageviews using this function.
if (!isFirstPageview) {
registerPageview();
} else {
isFirstPageview = false;
}
});
</script>
<Analytics />
```