Skip to content

Instantly share code, notes, and snippets.

@Slakinov
Created November 23, 2022 14:00
Show Gist options
  • Save Slakinov/6db5905de43995323065387d0f67fcda to your computer and use it in GitHub Desktop.
Save Slakinov/6db5905de43995323065387d0f67fcda to your computer and use it in GitHub Desktop.
Instant Google Analytics for SvelteKit, add to +layout.svelte
<script>
import { page } from '$app/stores';
import { browser } from '$app/environment';
import { onMount } from 'svelte';
export let id;
onMount(() => {
window.dataLayer = window.dataLayer || [];
window.gtag = function() { window.dataLayer.push(arguments) }
window.gtag('js', new Date());
window.gtag('config', id);
// console.log('GA init: '+id);
record($page.url.pathname);
});
$: {
if(browser) {
if (window.gtag != undefined) {
record($page.url.pathname);
}
}
}
function record(url) {
window.gtag('config', id, { 'page_path': url});
// console.log('GA: '+url);
}
</script>
<svelte:head>
<script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script>
</svelte:head>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment